六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 34|回复: 0

一个简单的JSON+AJAX

[复制链接]

升级  4.67%

13

主题

13

主题

13

主题

秀才

Rank: 2

积分
57
 楼主| 发表于 2013-1-29 10:52:53 | 显示全部楼层 |阅读模式
     最近把系统给彻彻底底的给清理了,在清理的时候居然发现以前的项目,和习题.所以拿出来给大家看看.也做个纪念.晕
内容如下:
我这里是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();    } }  
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表