7、使用JSON向服务器发送数据——ajax基础笔记

xiaoxiao2023-03-19  57

看过前面的例子后(使用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[0]); } 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" οnclick="doJSON();"/> </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(); } }

 运行结果:

 

 

转载请注明原文地址: https://www.6miu.com/read-4986699.html

最新回复(0)