ajax加载后台返回json数据注意事项!

w3school 上描述jquery的post方法,语法格式如下

jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)

其中dataType参数为可选。规定预期的服务器响应的数据类型。默认执行智能判断(xml、json、script 或 html)。
今天用的时候就真以为是智能判断而没有指定datatype类型,导致js无法解析后台传过来的json数据。
解决办法:
1.在php页面加上:
header('Content-Type:text/json;charset=utf-8');
2.在ajax成功后的回调函数中加上:
var json = JSON.parse(json);
3.指定dataType参数为json,比如:
$.post(url,data,function(){},'json');
最方便,最好使的无疑是第三种方法。
原文地址:https://www.cnblogs.com/flappyCoder/p/3822092.html