提交数据使用json代替xml
页面:jsonExample.jsp
<%@ page contentType="text/html; charset=GBK" %> <html> <head> <title> JSON示例 </title> <script type="text/javascript" src="zxml.src.js"></script> <script type="text/javascript" src="json.js"></script> <script type="text/javascript"> var xmlHttp; //创建对象 function createXMLHttpRequest(){ xmlHttp = zXmlHttp.createRequest(); } function doJSON(){ //得到Car对象 var car = getCarObject(); //用JSON字符串化car对象 var carAsJSON = car.toJSONString(); alert("汽车对象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.childNode[0]); } var responseText = document.createTextNode(xmlHttp.responseText); responseDiv.appendChild(responseText); } //得到Car对象 function getCarObject(){ return new Car("Dodge","Coronet R/T",1968,"yellow"); } //Car构造函数 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="发送JSON数据" onclick="doJSON();"/> </form> <h2> 服务器响应: </h2> <div id="serverResponse"> </div> </body> </html>
服务器:JSONExample.java
package ajaxbook.chap4; import java.io.*; import java.net.*; import java.text.ParseException; import javax.servlet.*; import javax.servlet.http.*; import org.json.JSONObject; public class JSONExample extends HttpServlet { //处理Post方法 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String json = readJSONStringFromRequestBody(request); //使用JSON绑字Ajax对象 JSONObject jsonObject = null; try { jsonObject = new JSONObject(json); } catch (ParseException pe) { System.out.println("ParseException: " + pe.toString()); } //返回输出结果 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); } //得到参数 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(); } }