前面有二篇 文章讲解 struts2 传递 json 数据的原理的 可以看一下,比较好理解
由于struts2实现了对json数据的封装,并转化为json字符串发送到前端,因此我们只需要写好配置文件,并把数据 装好就行了
action 类
package com.icreate.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.icreate.entity.User;
import com.opensymphony.xwork2.ActionSupport;
public class tAjax extends ActionSupport{
private static final long serialVersionUID = 1L;
Map<String,Object> map ;
public tAjax(){
map = new HashMap<String,Object>();
}
public static long getSerialVersionUID(){
return serialVersionUID;
}
public Map<String,Object> getMap(){
return this.map;
}
public void setMap(Map<String,Object> map){
this.map = map;
}
public String loadData(){
try{
User user1 = new User();
User user2 = new User();
user1.setId(1);
user1.setPassword("111");
user1.setUsername("jiajia");
user2.setId(2);
user2.setPassword("222");
user2.setUsername("taotao");
List<User> userList = new ArrayList<User>();
userList.add(user1);
userList.add(user2);
map.put("userList", userList);
JSONObject json = JSONObject.fromObject(map);
//将map对象转换成json类型数据,这里是测试而已,实现的json字符串是struts内部发送到前端
System.out.println("json To String:"+json.toString());
}catch(Exception e){
e.printStackTrace();
}
return SUCCESS;
}
}
前端js关键代码
if(xmlhttp.readyState==4&&xmlhttp.status==200)
{
alert("完成请求:"+xmlhttp.responseText);
var jsonObj = eval("("+xmlhttp.responseText+")");//把json字符串转化为json数据对象
alert("jsonObj.userList.length "+jsonObj.userList.length);
alert("jsonObj.userList[0].username "+jsonObj.userList[0].username);
alert("jsonObj.userList[1].id "+jsonObj.userList[1].id);
}
struts.xml
<package name="ajaxDemo" namespace="" extends="json-default">
<action name="tAjax" class="com.icreate.service.tAjax" method="loadData">
<result name="success" type="json">
<param name="root">map</param>
</result>
</action>
</package>
调试结果
json To String:{"userList":[{"id":1,"username":"jiajia","password":"111"},{"id":2,"username":"taotao","password":"222"}]}