1.ajax写法
function a4() {
$.post({
url : "${pageContext.request.contextPath}/ajax",
data : {
name : "前台好帅得程序员"
},
dataType : "json",
success : function(data) {
//解析单个对象时,直接data.出来即可,注意配置dataType:"json",将json转换成dom对象
alert(data.name);
alert(data.age);
}
-----------------------------------
//解析集合时,使用each
//在此说明$.each(data, function(x,y) {};中得x表示对象下标,y表示对象,可获取属性
success : function(data) {
$.each(data, function() {
console.log(this.name);
console.log(this.age);
})
}
-----------------------------------
});
}
servlet写法,返回json格式
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
List<User> users =new ArrayList<User>();
for (int i = 0; i <5; i++) {
User user = new User();
user.setName("张三"+i);
user.setAge("20"+i);
users.add(user);
}
/*
* String attribute = (String) request.getParameter("name");
* User user = new
* User(); user.setName("张三"); user.setAge("20");
*/
Gson gson = new Gson();
String json = gson.toJson(users);
response.getWriter().print(json); // 返回页面对应data值
}
$(function(){
$("#btn").click(function(){
//发送ajax
$.post("${pageContext.request.contextPath}/ajax","name="+$("#inp").val(),
function(data){
$(data).each(function(){
console.log(this.name);
})
},"json");
})
})