在ajax中返回數據有兩種方式:第一個用responsetext;另外一種是用responseXML的方式,由於XML解析效率低下和占用的流量的確大了很多,所以序列化JSON便受到廣大web程序員的喜愛。后台可以復雜的數據結構(如數組,自定義類等)序列成字符串后回傳給前台js,而前台javascript可以用很方便 的用eval函數,json2.js(可以到www.json.org下載)等輕松的完成解析,然后呈現出來。
后台我用的是java的Servlet來進行業務處理。
在eclipse新建好web工程后,首先創建一個jsp文件,添加一個按扭,和一個div。
<script type="text/javascript"> function getAjaxJson() { httpGet("myServlet", "GET", "msg=123"); } </script> </head> <body> <strong>AJAX JSON序列化示例</strong> <hr> <input type="button" value="GET操作" onclick="getAjaxJson()"> <hr> <div id="showout"></div> </body>
web.xml配置:
<url-pattern>中的字段myServlet是腳本文件的url.
httpGet("myServlet","GET","msg=123");
<servlet-name>的字段是服務器端servlet類的類名。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>jsonexample</display-name> <servlet> <servlet-name>myServlet</servlet-name> <servlet-class>com.myServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>/myServlet</url-pattern> </servlet-mapping> </web-app>
完成以上任務以后,我們再來編寫ajax發送http請求的腳本,新建一個腳本並引入到網頁中,在head標簽之間。
<script type="text/javascript" src="script/ajaxRequest.js"></script>
/* * 函數名:getTransport * 功能: 根據不同的瀏覽器對象創建 XMLHttpRequest對象並返回,如果瀏覽器不支持該對象,則返回undefined. */ var xmlhttp=null; function getHttpRequest() { try { xmlhttp=new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) { try { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } catch(e1) { xmlhttp=new XMLHttpRequest(); } } } function httpGet(url,method,data) { getHttpRequest(); xmlhttp.open(method,url +"?"+data,true); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Content-Length",data.length); xmlhttp.onreadystatechange=callback; xmlhttp.send (null); } function callback() { if(xmlhttp.readyState==4) { if(xmlhttp.status==200) { //要實現的操作 var xmlDoc=xmlhttp.responseText; var data=eval(xmlDoc); document.getElementById("showout").innerHTML+=data[0].userId+","+data[0].userName+","+data[0].userSex+"<br>"; document.getElementById("showout").innerHTML+=data[1].userId+","+data[1].userName+","+data[1].userSex+"<br>"; } else { document.getElementById("showout").innerHTML="AJAX Server error!"; } } }
這樣前台的編碼就完成了,然后添加后的處理代碼,新建一個servlet類:
Json的架包有:json-lib-2.3-jdk15.jar,commons-beanutils-1.7.0.jar,commons-collections-3.1.jar,commons-lang-2.3.jar,ezmorph-1.0.6.jar,commons-logging.jar。可以到csdn:http://download.csdn.net/detail/tyfengyu/4478154下載后,buildpath進去。
package com; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import net.sf.json.*; public class myServlet extends HttpServlet { private static final long serialVersionUID=1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //指定 去除客戶端頁面的緩存 ClearCache(response); //制造假數據 ArrayList<UserModel> list=new ArrayList<UserModel>(); UserModel user1=new UserModel();//用戶對象1 user1.setUserId(1); user1.setUserName("哈哈"); user1.setUserSex("男"); list.add(user1); UserModel user2=new UserModel();//用戶對象2 user2.setUserId(2); user2.setUserName("呵呵"); user2.setUserSex("女"); list.add(user2); //將List轉化為JSON //設置編碼 response.setCharacterEncoding("utf-8"); //寫入到前台 JSONArray json1=JSONArray.fromObject(list); response.getWriter().write(json1.toString()); System.out.print(json1.toString()); response.getWriter().flush(); response.getWriter().close(); } public void ClearCache(HttpServletResponse response) { //指定 去除客戶端頁面的緩存 response.setHeader("pragma", "no-cache"); response.setHeader("cache-control", "no-cache"); response.setHeader("expires", "0"); } }
UserModel類:
必須顯示聲明缺省的構造函數,屬性要用get 、set方法。
package com; public class UserModel { /** * @param args */ private int UserId; private String UserName; private String UserSex; public UserModel() { //super(); } /** * @return the userId */ public int getUserId() { return UserId; } /** * @param userId the userId to set */ public void setUserId(int userId) { UserId = userId; } /** * @return the userName */ public String getUserName() { return UserName; } /** * @param userName the userName to set */ public void setUserName(String userName) { UserName = userName; } /** * @return the userSex */ public String getUserSex() { return UserSex; } /** * @param userSex the userSex to set */ public void setUserSex(String userSex) { UserSex = userSex; } }
這樣就完成ajax+jsp用JSON進行數據傳輸的例子。
效果:
參考:http://www.cnblogs.com/lsnproj/archive/2012/02/09/2341524.html
轉載本文請標明出處。