duanrenzou1619
2014-08-20 13:31
浏览 92

JQuery $ .ajax请求json响应

A JSON returned as response to this request is not recognized.

request = $.ajax({
        url: "form_handler.php",
        type: "post",
        dataType: "json",
        data: serializedData
});

The php code in form_handler.php which returns the response:

if ($success) {
    echo json_encode(array("success"=>"false"), JSON_PRETTY_PRINT); 
}
else
{
    echo json_encode(array("success"=>"true"), JSON_PRETTY_PRINT); 
}

And thus in:

request.done(data) 
{
    alert(data.success);     // error: cannot read property of 'success' of null 
}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • douji8033 2014-08-20 13:55
    已采纳

    I'm writing this as a wrap up of the answers and comments posted.

    As @jetawe and @FelixKling pointed out, it would be a best practice to specify the Content-Type of the response, so add this at the head of the php script:

    header('Content-Type: application/json');
    

    @hindmost pointed out that the script is not failing since jqXHR.done() is actually called.

    My guess is that there is a failure decoding the json object when $.ajax automatically decodes it (because of dataType: "json")

    As @PaulRoub noticed, JSON_PRETTY_PRINT exists from the PHP version 5.4 so, if you have an older version of PHP, that constant wouldn't exists, throwing an error of level E_NOTICE and assuming the value null. Passing null (equal to 0) as a value json_encode would work anyway (assuming default behavior)

    My second guess is that you have display_errors = 1 and error_reporting = E_ALL so PHP is printing out the error breaking the json.

    I hope I guessed right!

    已采纳该答案
    打赏 评论
  • doushan7077 2014-08-20 13:34

    That code looks ok, but maybe handling it all in the ajax call itself would help debug your issue.

    $.ajax({
            url: "form_handler.php",
            type: "post",
            dataType: "json",
            data: serializedData,
        success: function(data){
             console.log(data);
             console.log(data.success);
             console.log($.parseJSON(data));
        }
    });
    

    Please add your response object if you get one so we can see the structure - and i'll update my answer.

    打赏 评论
  • dspows0637 2014-08-20 13:35

    you have to send JSON header in , set it in your php file

    header('Content-Type: application/json');
    echo json_encode(array("success"=>"false"), JSON_PRETTY_PRINT);
    
    打赏 评论
  • dsgwdigu84950 2014-08-20 13:42

    This is Ajax request:

    jquery.ajax({
                    type: "POST",
                    url: url,
                    data: data,
                    success: function(serverData) {
                        var data = JSON.parse(serverData);
                        callback(data);
                    }
                });
    

    Php response:

    echo json_encode(array('success' => 'true'));
    
    打赏 评论

相关推荐 更多相似问题