一个简单的JSON+AJAX
最近把系统给彻彻底底的给清理了,在清理的时候居然发现以前的项目,和习题.所以拿出来给大家看看.也做个纪念.晕内容如下:
我这里是json.js(放在index.jsp中,记得一定要放在所以js的第一个引入),json.jar(放在bin下面).
1:首先你建一个js文件
内容如下:
var xmlHttp;
functioncreateXMLHttpRequest(){if(window.ActiveXObject){ xmlHttp= newActiveXObject("Microsoft.XMLHTTP");} else if(window.XMLHttpRequest){ xmlHttp= newXMLHttpRequest();} } //创建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(){ varperson=getPerson(); //使用json.js库里的stringify()方法将person对象转换成Json字符串 varpersonAsJSON=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);}functionhandleStateChange(){ if (xmlHttp.readyState== 4 ){ if (xmlHttp.status== 200 ){ parseResults(); } } }functionparseResults(){ varresponseDiv=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= newJSONObject(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);}//读取传递过来的信息privateString readJSONStringFromRequestBody(HttpServletRequest request) { StringBuffer json= newStringBuffer(); 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()); } returnjson.toString(); } }
页:
[1]