当前位置:Gxlcms > PHP教程 > jqueryajaxjson怪异的有关问题

jqueryajaxjson怪异的有关问题

时间:2021-07-01 10:21:17 帮助过:7人阅读

jquery ajax json 怪异的问题
js代码
$.ajax({
type: "post",
url: "/test1.php",
dataType: "json",
timeout : 16000,
data:{cid:n},
success: function(msg){
if(1 == msg.status){
alert('ok');
}else if(0 == msg.status){
alert('sorry')
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus+","+errorThrown);
}
});

php代码
header("Content-type: text/html; charset=utf-8"); //这一句话,为的是utf8格式输出,有无这句话,都是一样执行ajax error分支
$menu=array("status"=>1);
exit(json_encode($menu));

去除js的dataType: "json",正常执行success分支;
使用jquery1.3.2 也正常执行success分支;但只要使用1.6,并且指定dataType:"json",立马执行error分支,报“parsererror,No conversion from text to json” json解析问题;

难道php的json_encode()函数,转换数组至json格式也会有问题?
------解决思路----------------------
因为你有 dataType: "json"
所以进入 ajax error分支 的前提是返回的数据不是 json 格式的
parsererror,No conversion from text to json (json转换失败)也佐证了这一点

为什么会转换失败呢?多半是你的 php 程序保存成了有 utf-8 BOM 头的格式了
这一点你可以通过:
2.php
echo bin2hex(file_get_contents('http://localhost/1.php'));
看到。输出结果中开始的 efbbbf 就是 BOM 头

人气教程排行