1. 前言
dataType: 要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。
response.setContentType("text/html"); //一般默认返回的类型自己指定(有xmlDoc、jsonObj、html、text这几种)
如果返回字符串是json的字符串,希望返回的数据为json对象,可以在返回时设置
response.setContentType("text/json");
或者
让其返回json字符串然后再转成json对象(见http://www.cnblogs.com/fanbi/p/7289551.html)。
2.方法
第一种
JS代码:
$.ajax({
type: 'POST',
data : {
mode:"getData",
id:id,
},
url : './data',
dataType: 'json', //添加这一条语句
success: function(msg) {
if(msg.status == "success"){
//todo sth
}
}
});
Java代码:
String status = "{"status":"success"}";
//response.setContentType("text/json");
IOUtils.write(status.getBytes(), response.getOutputStream());
//或者
try (PrintWriter writer = response.getWriter();) {
writer.write(status);
writer.flush();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
第二种
JS代码:
$.ajax({
type: 'POST',
data : {
mode:"getData",
id:id,
},
url : './data',
success: function(msg) {
if(msg.status == "success"){
//todo sth
}
}
});
Java代码:
String status = "{"status":"success"}";
response.setContentType("text/json");
IOUtils.write(status.getBytes(), response.getOutputStream());
//或者
try (PrintWriter writer = response.getWriter();) {
writer.write(status);
writer.flush();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}