簡體   English   中英

語法錯誤{},AJAX成功無法讀取PHP返回的JSON

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM