[英]Syntax Error{} AJAX success cannot read JSON returned from PHP
我需要一些帮助。 我正在向服务器发送简单的请求,我期望的返回值是JSON作为数据类型。 但是,当我在开发工具控制台日志中签入时,会收到“ parsererror SyntaxError {}”和“ parsererror”。
我该怎么做呢? 下面是代码。
jQuery查询
$(':submit').live('click', function() {
$.ajax({
type : 'post',
url: 'testJSON.php',
beforeSend:console.log('sending...'),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
console.log(data.status);
// do magic
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
},
complete: function(XMLHttpRequest, status) {
console.log(status);
}
});
return false;
});
这是testJSON.php
<?php
$data = array(
"status" => 1,
"firstname" => "foo",
"lastname" => "bar",
);
header('Content-type: application/json; charset=utf-8" ');
echo json_encode($data);
exit();
?>
仅供参考,我使用最新版本的WAMP。 任何帮助,非常感谢。
将内容的标头设置为json类型...这是设置标头类型的示例。
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
从jQuery 1.4开始,严格按照JSON数据进行解析。
拒绝任何格式错误的JSON并引发解析错误。
从这里删除"
header('Content-type: application/json; charset=utf-8" ');
应该
header('Content-type: application/json; charset=utf-8');
我尝试了您的代码,但在beforeSend参数上遇到了错误。 语句应封装在一个函数中:
...
beforeSend: function() {console.log('sending...')},
...
之后,一切正常。 也许还取决于jQuery版本。 您使用了哪一个? 我尝试使用1.8.1及更高版本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.