日期:2014-05-16 浏览次数:20664 次
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>MyHtml.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="json2.js"></script> <script type="text/javascript"> var xmlHttp; function doJson() { var cars = new car("奔驰","SLCAR00004500",50000); var carAsJson=JSON.stringify(cars); 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 car(carname,carno,carprice) { this.carName=carname; this.carNo=carno; this.carPrice=carprice; } function createXMLHttpRequest() { if(window.XMLHttpRequest) { xmlHttp=new XMLHttpRequest(); } if(window.ActiveXObject) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } function handleStateChange() { if(xmlHttp.readyState ==4 && xmlHttp.status==200) { parseResult(); } } function parseResult() { var responseDiv = document.getElementById("serverResponse"); if(responseDiv.hasChildNodes()) { responseDiv.removeChild(responseDiv.childNodes[0]); } var responseText = document.createTextNode(xmlHttp.responseText); responseDiv.appendChild(responseText); } </script> </head> <body> <form action="#"> <input type="button" name="button" value="show Json" onclick="doJson()" /> </form> <h2>Server response:</h2> <div id="serverResponse"></div> </body> </html>
package com.suning.study.ajax.servlet; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; @SuppressWarnings("serial") public class AjaXDemo extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String json = readJsonStringFromRequest(request); JSONObject obj=null; String responseText =""; try { obj=new JSONObject(json); responseText="The car is a car[carName:"+obj.getString("carName")+",carNo:"+obj.getString("carNo") +",carPrice:"+obj.getDouble("carPrice&qu