1.首先要準備一個JSONUtile工具類,來實現數據的JSON轉換javascript
具體代碼能夠從這裏下載:html
java普通類編譯成json但只是當前類的有getter、setter方法的版本:java
http://download.csdn.net/detail/songylwq/5896369ajax
java本身修改的支持public屬性、父類屬性的json自動編譯的工具類版本:json
http://download.csdn.net/detail/songylwq/5896385框架
2.struts2框架搭建好後,在BaseAction中構建變量、方法dom
protected String ajaxData; public String getAjaxData() { return ajaxData; } public void setAjaxData(String ajaxData) { this.ajaxData = ajaxData; }
3.在struts.xml配置文件中配置全局返回頁面jsp
<global-results> <result name="ajax" >/ajax.jsp</result> </global-results>
<%@ page language="java" pageEncoding="UTF-8" import="org.main.common.util.*"%> <%@ taglib prefix="s" uri="/struts-tags"%> <s:property value="ajaxData" escape="false"/>
public String test_json() throws Exception{
//邏輯代碼
ajaxData = 返回數據;
return SUCCESS;
}
4.頁面中js代碼:工具
<script type="text/javascript"> function testJSON(){ $.ajax({url:'test_json.action', data:{time:Math.random()}, dataType: "json", success:function(res){ alert(res); $.each(res,function(i,n){ alert(i+":"+n["orderNo"]); }) } }); } </script>