本文主要为大家分享了ajax获取显示json数据的一种方法,供大家参考,具体内容如下
1、首先前台用ajax,其中注意datatype一定要选择json方式,action成功返回给页面的json内容是这样的[{number:v006,names:lilei}],可见comment['names']对应names:lilei,comment['number']对应number:v006。
$.ajax({
type: "post",
url:'apply/mystudent.action?',
cache: false,
datatype : "json",
success: function(data){
$.each(data, function(commentindex, comment){
alert("姓名"+ comment['names']);
alert("学号"+comment['number']);
});
}
});
2、ajax的url指向在java的action中mystudent方法,返回的list其实是一个对象student,包括了names和nunmber字段
public string mystudent() throws exception{
list list=priceservice.query();//调用接口实现类
this.jsonutil(list);
return null;
}
3、action页面专门写一个方法jsonutil来做为json方法
// 调用json工具方法,传入参数alist
public void jsonutil(object accountlist) throws exception {
httpservletresponse response = servletactioncontext.getresponse();
log.info("json格式:" + accountlist.tostring());
string returnjson = jsonconvert.returnjson(accountlist);
response.setcharacterencoding("utf-8");
response.getwriter().println(returnjson);
}
4、我用的是一种比较新的json包jackson
import java.io.stringwriter;
import org.codehaus.jackson.map.objectmapper;
public class jsonconvert {
static string jsonstr;
public static string returnjson(object object) throws exception{
objectmapper objectmapper = new objectmapper();
stringwriter stringwriter = new stringwriter();
objectmapper.writevalue(stringwriter, object);
jsonstr = stringwriter.tostring();
return jsonstr;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助。
更多java中使用json与前台ajax数据交互的方法。