实现原理:从Action中返回JSON格式的字符串,在ajax中获取到data,并将其转换成js的JSON数据,然后遍历
注:亦可在Java代码就转换为JSON格式,使用JSONArray jsonArray=JSONArray.fromObject(string),写write(jsonArray.toString());这时在JS里就不需要使用eval()转换直接遍历
Struts.xml
<action name="myAjaxAction" class="myAction" method="myAjaxAction"><interceptor-ref name="mystack" /></action>
Action方法
public void myAjaxAction(){
try{
HttpServletResponse responses = ServletActionContext.getResponse();
responses.setCharacterEncoding("utf-8");
PrintWriter writer = responses.getWriter();
//设置JSON数据,\"是转义符,实际内容为:[{name:"张三",age:12},{name:"李四",age:11},{name:"王五",age:13},{name:"小六",age:14}];
String string="[{name:\"张三\",age:12},{name:\"李四\",age:11},{name:\"王五\",age:13},{name:\"小六\",age:14}]";
writer.write(string);
writer.flush();
writer.close();
}catch (Exception e) {
// TODO: handle exception
}
}
HTML
<input type="button" value="测试JSON" οnclick="ajaxJson()"/>
JS代码
function ajaxJson(){
$.ajax({
type:"post",
url:"myAjaxAction.action",
async:true,
success:function(data) {
var obj=eval("("+data+")");//将数据转换成json类型
for(var i in obj){//遍历Json数据
alert("姓名:"+obj[i].name+" 年龄:"+obj[i].age );
}
},
error:function(e) {
alert("验证失败!");
}
});
}