日期:2014-05-16  浏览次数:20496 次

一个简单的JSON+AJAX

? ? ?最近把系统给彻彻底底的给清理了,在清理的时候居然发现以前的项目,和习题.所以拿出来给大家看看.也做个纪念.晕

内容如下:

我这里是json.js(放在index.jsp中,记得一定要放在所以js的第一个引入),json.jar(放在bin下面).

? ? ?1:首先你建一个js文件

内容如下:

? ? ?var xmlHttp;

function  createXMLHttpRequest()  {
  if  (window.ActiveXObject)  {
     xmlHttp  =   new  ActiveXObject("Microsoft.XMLHTTP");
  }  
  else   if  (window.XMLHttpRequest)  {
     xmlHttp  =   new  XMLHttpRequest();
  } 
} 
//创建Person类有参构造器
function Person(name,age,gender,birthday){
	this.age = age;
	this.gender = gender;
	this.name = name;
	this.birthday = birthday;
}
//创建一个Person的对象
function getPerson(){
	return new Person("coco",25,true,"1988-08-08");
}
//发起ajax请求
function doJSON(){
   var  person  =  getPerson();
   
   //使用json.js库里的stringify()方法将person对象转换成Json字符串 
   var  personAsJSON  =  JSON.stringify(person);
   alert( " Car object as JSON:\n  "   +  personAsJSON);
   
   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(personAsJSON);
}

function  handleStateChange()  {
    if (xmlHttp.readyState  ==   4 )  {
        if (xmlHttp.status  ==   200 )  {
            parseResults();
        } 
    } 
}

function  parseResults()  {
    var  responseDiv  =  window.document.getElementById("responseDiv");
    var content = xmlHttp.responseText
    responseDiv.value = content;
}

?

?

下面是处理的Servlet

?

?

public class JSONExample extends HttpServlet{
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String json  =  readJSONStringFromRequestBody(req);
        
        // Use the JSON-Java binding library to create a JSON object in Java 
        JSONObject jsonObject  =   null ;
        String responseText = null;
        try{
           //将json字符串转化为JsonObject对象
           jsonObject  =   new  JSONObject(json);
           String gender = jsonObject.getBoolean("gender")?"男":"女";
           responseText  =   "You name is  "   +  jsonObject.getString( "name" )  +   " age is  " 
           +  jsonObject.getInt( "age" )  +   "  gender is "   + gender
           +  "  birthday is  "   +  jsonObject.getString( "birthday" );
           System.out.println("responseText="+responseText);
        } 
         catch (Exception pe)  {
           System.out.println( " ParseException:  "   +  pe.toString());
        } 
        //设置字符集,和页面编码统一
        resp.setCharacterEncoding("utf-8");
        resp.setContentType( "text/xml" );
        resp.getWriter().print(responseText);
	}

	//读取传递过来的信息
	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();
    } 
}
?

?