本人后台是java,不过.net和java一样哦!
如果后台返回的JSON 定义String data = "{'result':'ok'}";
哪么会造成前台JSON解析错误,错误为"SyntaxError: 语法错误"
我们应该这样写 String data = "{'\"result\":\"ok\"}" ;
这样写就不会有问题了!
即String data = "{'result':'ok'}"; ---> String data = "{'\"result\":\"ok\"}" ;
ajax代码
jQuery.ajax({
url: "${pageContext.request.contextPath}/admin/buildHtml",
type: "post",
data: obj,
dataType: "json",
success: function(msg) {
alert(msg);
var json= eval('(' + msg + ')');
alert(json.result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
alert(errorThrown);
},
complete: function(XMLHttpRequest, textStatus) {
this; // 调用本次AJAX请求时传递的options参数
}
});
后台老板代码
try {
PrintWriter writer = response.getWriter();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8"); //这样前台接受的将直接是JSON对象
writer.print(data);
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}