7、使用JSON向服务器发送数据——ajax基础笔记
看过前面的例子后(使用XML向服务器发送复杂的数据结构),你可能会改变注意。通过串连接来创建XML串并不能,这也不是用来生成或修改XML数据结构的健壮的技术。使用JSON向服务器发送数据
该示例了如果使用JSON将JavaScript对象转换为串格式,并使用Ajax技术将这个串发送到服务器,然后服务根据这个串创建一个对象。
jsonExample.html清单:
<!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(); //使用JSON脚本库把JavaScript对象转换成Json字符串 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); } 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" /></form> <h2>Server Response:</h2><div id="serverResponse"></div></body></html>JSONExample.java清单:
package ajaxbook.chap3;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 { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String json = readJSONStringFromRequestBody(request); //使用 JSON-Java 特定库创建Json Java 对象 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); } //从客户端读取JSON字符串 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(); }} 运行结果:
http://dl.iteye.com/upload/attachment/157654/5e1f105a-f5ef-38f9-811f-39ceb5adc045.gif
页:
[1]