`
zranye
  • 浏览: 25957 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

使用Json的Ajax实例

    博客分类:
  • JAVA
阅读更多

今天公司要求尝试一下Ajax的学习,作为新人,学习新东西是一个任务,也是很乐意做的一件事情。那么就记录一下学到的内容。

首先是我还很不熟悉的html页面的前端的代码(用json封装数据的方式):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"   
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<title>JSON Example</title>  
  
<script type="text/javascript" src="json.js"></script>  
<script type="text/javascript">  
  
var xmlHttp;   
  
function createXMLHttpRequest() {   
    if (window.ActiveXObject) {   
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");   
    }    
    else if (window.XMLHttpRequest) {   
        xmlHttp = new XMLHttpRequest();   
    }   
}   
       
function doJSON() {   
    var car = getCarObject();   
       
    //Use the JSON JavaScript library to stringify the Car object   
    var carAsJSON = JSON.stringify(car);   
    alert("Car object as JSON:\n " + carAsJSON);   
       
    var url = "JSONExample?timeStamp=" + new Date().getTime();   
       
    createXMLHttpRequest();   
    xmlHttp.open("POST", url, true);   
    xmlHttp.onreadystatechange = handleStateChange;   
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");       
    xmlHttp.send(carAsJSON);
}   
       
function handleStateChange() {   
    if(xmlHttp.readyState == 4) {   
        if(xmlHttp.status == 200) {   
            parseResults();   
        }   
    }   
}   
  
function parseResults() {   
    var responseDiv = document.getElementById("serverResponse");   
    if(responseDiv.hasChildNodes()) {   
        responseDiv.removeChild(responseDiv.childNodes[0]);   
    }   
       
    var responseText = document.createTextNode(xmlHttp.responseText);   
    responseDiv.appendChild(responseText);   
}   
  
function getCarObject() {   
    return new Car("Dodge", "Coronet R/T", 1968, "yellow");   
}   
  
function Car(make, model, year, color) {   
    this.make = make;   
    this.model = model;   
    this.year = year;   
    this.color = color;
}   
  
</script>  
</head>  
  
<body>  
  
  <br/><br/>  
  <form action="#">  
      <input type="button" value="Click here to send JSON data to the server" onclick="doJSON();"/>  
  </form>  
  <h2>Server Response:</h2>  
  
  <div id="serverResponse"></div>  
  
</body>  
</html>  

    这里有用到json的jar包。Json在我看来是一个封装了很多键值对的一些数据的集合(暂时就这么理解吧),用Json再加上Post的请求方式来对服务器请求数据,可以有效地服务器的负担。

      这里有必要对html代码中异步请求的一些核心功能进行解释,就算是为以后忘记了这一方法的我和还没学会Ajax的新手写的吧。button点击之后,触发doJSON()的事件,通过var car = getCarObject();调用了测试数据function Car()里面的数据,然后创建一个xmlHttp的对象--createXMLHttpRequest();然后再通过xmlHttp对象的open()和send()方法,就算是往服务器传输了数据。就本人理解,所谓异步,是指在open()和send()之间,xmlHttp对象开启了一个onreadystagechange这样一个监听器,负责监听工作的代码块是function handleStageChange()方法。这样开启了一个请求状态的监听器之后,就可以对服务器的响应以parseResult()的方法作出回应,而不是通过刷新来响应服务器的返回的请求。在parseResult()的方法里,做了很简单的用js改变文本的动作,以观察是否有变化。

       在java代码这块,我们只需要写一个简单的Servlet就可以扑捉到在前台通过send()发送过来的请求。代码如下:

 

package com.servlet;

import java.io.*;   
import java.net.*;   
import java.text.ParseException;   
import javax.servlet.*;   
import javax.servlet.http.*;    

import org.json.JSONException;
import org.json.JSONObject;

  
public class JSONExample extends HttpServlet {   
       
    protected void doPost(HttpServletRequest request, HttpServletResponse response)   
    throws ServletException, IOException {   
        String json = readJSONStringFromRequestBody(request);   
           
        //Use the JSON-Java binding library to create a JSON object in Java   
        JSONObject jsonObject = null;   
        try {   
            jsonObject = new JSONObject(json);  
            String responseText = "You have a " + jsonObject.getInt("year") + " "  
            + jsonObject.getString("make") + " " + jsonObject.getString("model")   
            + " " + " that is " + jsonObject.getString("color") + " in color.";   
            response.setContentType("text/xml");   
            response.getWriter().print(responseText);   
        }    catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   
           
           
    }   
  
    private String readJSONStringFromRequestBody(HttpServletRequest request){   
        StringBuffer json = new StringBuffer();   
        String line = null;   
        try {   
            BufferedReader reader = request.getReader();   
            while((line = reader.readLine()) != null) {   
                json.append(line);   
            }   
        }
        catch(Exception e) {   
            System.out.println("Error reading JSON string: " + e.toString());   
        }   
        return json.toString();   
    }
}  

 一些包结构也直接复制上来了,可以自己做一些改动,有用到的jar包,在下面可以找到。做后台的,对java这一块应该很容易理解,就不多作解释。

      根据我的文件系统也贴上我的web.xml吧。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<servlet>
		<servlet-name>JSONExample</servlet-name>
		<servlet-class>com.servlet.JSONExample</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>JSONExample</servlet-name>
		<url-pattern>/JSONExample</url-pattern>
	</servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 一个简单的Demo,希望可以帮助到一些朋友尽快搞定,因为自己也是费了点功夫才搞出来的,而工作中没有多少时间可以给我们学习,所以,码农们一起共勉吧。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics