语法Error {} AJAX成功无法读取PHP返回的JSON

时间:2013-04-29 10:52:17

标签: php jquery ajax json

我需要一些帮助。我正在向服务器发送简单请求,我期望的返回是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。非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

将内容的标题设置为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都会被拒绝,并且会抛出一个解析错误。

答案 1 :(得分:0)

从此处删除"

header('Content-type: application/json; charset=utf-8" ');

应该是

header('Content-type: application/json; charset=utf-8');

答案 2 :(得分:0)

我尝试了您的代码,我在 beforeSend 参数中出错。这些陈述应封装在一个函数中:

...    
beforeSend: function() {console.log('sending...')},
...

之后一切正常。也许它还取决于jQuery版本。你用的是哪一个?我尝试使用版本1.8.1及更高版本