实现方法:使用JSONArry对象,将装载在list里的实体类集转化为json,在jq中使用eval("("+data+")")方法将其转化为jq可读取的json数据
Struts.xml
<action name="myAjaxAction" class="readDocumentAction" method="myAjaxAction"><interceptor-ref name="mystack" /></action>
Action.java
public void myAjaxAction(){
try{
HttpServletResponse responses = ServletActionContext.getResponse();
//设置编码格式,注:位置需在list前,否则utf-8格式会不对list起作用,导致乱码问题
responses.setCharacterEncoding("utf-8");
PrintWriter writer = responses.getWriter();
//创建userInfos对象的集合
List<UserInfos> list=new ArrayList<UserInfos>();
//制作数据
UserInfos userInfos1=new UserInfos();
userInfos1.setId("001");
userInfos1.setName("小明");
UserInfos userInfos2=new UserInfos();
userInfos2.setId("002");
userInfos2.setName("小红");
UserInfos userInfos3=new UserInfos();
userInfos3.setId("003");
userInfos3.setName("小黑");
//添加数据
list.add(userInfos1);
list.add(userInfos2);
list.add(userInfos3);
//将List转换为JSON
JSONArray jsonArray=JSONArray.fromObject(list);
//写入到前台
writer.write(jsonArray.toString());
writer.flush();
writer.close();
}catch (Exception e) {
// TODO: handle exception
}
}
JS
function ajaxJson(){
$.ajax({
type:"post",
url:"myAjaxAction.action",
async:true,
success:function(data) {//获取返回值
alert(data);
var obj=eval("("+data+")");
alert(obj);
for(var i in obj){
alert("ID:"+obj[i].id+"\nName:"+obj[i].name);
}
},
error:function(e) {
alert("验证失败!");
}
});
}
HTML
<input type="button" value="测试JSON" οnclick="ajaxJson()"/>