jquery ajax json 怪异的有关问题

WBOY
Release: 2016-06-13 12:26:53
Original
1299 people have browsed it

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

<?php<br />echo bin2hex(file_get_contents('http://localhost/1.php'));<br />
Copy after login
看到。输出结果中开始的 efbbbf 就是 BOM 头

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!