这里主要通过代码的形式展示ajax同后台交互的案例:
一:后台返回json数据:
ajax代码如下:
function myAjaxFunction() {
var merchantId = $('#merchantId').val());
$.ajax({
type: 'POST',
url: "****/****.action",
data: {
"merchantId": merchantId
},
async: false,
dataType: 'json',
success: function (data) {
if (typeof(data.status)!="undefined" && data.status == "1" ) {
//****处理逻辑
} else if (typeof(data.status)!="undefined" && data.status == "0") {
$.messager.alert('提示', "异步加载失败", 'error');
}
},
error: function () {
$.messager.alert('提示', '服务器未响应,请稍后再试!', 'error');
return false;
}
});
}
后台action中需要定义传递参数的属性(上面为merchantId),并提供getter、setter方法就OK了。
JSONObject jsonResult = new JSONObject();
try {
T result = ****();
if(result != null) {
jsonResult.put("status", 1);
jsonResult.put("result", result.getResult());
} else {
jsonResult.put("status", 0);
}
} catch (Exception e) {
logger.error(e);
jsonResult.put("status", 0);
}
this.ajaxPrintPage(jsonResult);
其中ajaxPrintPage为向ajax返回结果的方法:
public void ajaxPrintPage(Object obj) {
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
PrintWriter writer = null;
try {
try {
writer = response.getWriter();
if(null == obj) {
writer.print("");
} else {
writer.print(obj.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
} finally {
if(writer != null) {
writer.flush();
writer.close();
}
}
}