AJAX请求
$.ajax({
type: "post",
url: "/address/get.action",
data: {
addressId: addressId
},
success: function (address) {
//解析JSON字符串
var ad = JSON.parse(address);
console.log("请求成功");
//ajax渲染
$("#adId").val(ad.id);
$("#receiveName").val(ad.uname);
$("#fullAddress").val(ad.address);
$("#postalCode").val(ad.code1);
$("#phone").val(ad.phone);
$("#mobile").val(ad.mobile);
},
error: function () {
console.log("请求失败");
}
})
action
public String get() {
address = addressService.get(addressId);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
//obiect转json
JSONObject json = JSONObject.fromObject(address);
try {
//返回给ajax
response.getWriter().print(json);
} catch (IOException e) {
e.printStackTrace();
}
return null;//异步请求返回值为空
}
AJAX渲染
//解析JSON字符串
var ad = JSON.parse(address);
console.log("请求成功");
//ajax渲染
$("#adId").val(ad.id);
$("#receiveName").val(ad.uname);
$("#fullAddress").val(ad.address);
$("#postalCode").val(ad.code1);
$("#phone").val(ad.phone);
$("#mobile").val(ad.mobile);
主要是这三个步骤,有三个注意点:
- 对象json化 JSONObject.fromObject(object);
- action方法无返回值,通过成员变量或者response.getWriter().print();返回给ajax (没试过成员变量行不行,使用response时记得response.setCharacterEncoding(“UTF-8”)设置编码)
- AJAX对回调函数返回值进行json解析 JSON.parse(data),打印出来解析后的数据分析渲染到页面