发送ajax请求到后台(Java),debug后台数据没有问题,甚至自己写的结果
PrintWriter out;
try {
out=response.getWriter();
out.write("{'id':12,'name':'ok' }");
} catch (IOException e) {
e.printStackTrace();
}
但是返回结果进error方法
error:function(xhr,status,error){
throw new Error("status:"+status+"; Error:"+error);
}
具体结果:
Uncaught Error: status:parsererror; Error:SyntaxError: Unexpected token <
求教问题出在哪里?
$ajax 中加入 dataType: 'json'
如果后台用的是springmvc,可能是controller方法里没加@Responsebody,然后ajax中的dataType:“json”
试试这样:
out.write("{\"id\":12,\"name\":\"ok\"}");
当浏览器原生 支持JSON
对象的时候, 它所要求的 JSON
格式是严格的, 即字符串,是以双引号引起来的,
而你提供的代码中输出的内容是 单引号, 不是 标准的JSON格式的数据, 所以进的 error
.
不过根据你给出的报错提示,我感觉是你的后端输出的是HTML代码, 而不是 JSON格式的字符串.
可以提供一下你后端最终输出到浏览器端的内容吗?
看看夏天博客的这一篇,很详细的ajax。http://www.xtwind.com/simple-ajax.html
直接请求这个url看看你的返回结果。
java后台返回的json数据使用json序列化反序列化类库
注意服务器写出响应的编码
注意服务器写响应的content-type
注意ajax解析的数据类型