2015-08-09 29 views
2

在我的js文件名爲Ajax的錯誤回調我打電話以下:當有效的JSON被重新調整

$.ajax({ 
      type: "POST", 
      dataType: "application/json", 
      url: "php/parseFunctions.php", 
      data: {data:queryObj}, 
      success: function(response) { 
      theFunction(response); 
      }, 
      complete: function(response) { 
      theFunction(response); 
      }, 
      error: function(response) { 
      theFunction(response); // response = Object {readyState: 4, responseText: "{"found":0}", status: 200, statusText: "OK" 

      } 
    }); 

在我php/parseFunctions.php我:

$returnResults = array(); 
$returnResults['found']=count($returnResults); 
echo json_encode($returnResults); 
exit; 

我期待success回撥被叫和response成爲json對象{"found":"0"}

取而代之,error回調被調用,並且response = Object {readyState: 4, responseText: "{"found":"0"}", status: 200, statusText: "OK"}

我讀過如果返回的JSON無效,會發生這種情況,但我不喜歡它。

我在這裏做錯了什麼?

回答

6

我相信問題在於你的dataType屬性。您已將其設置爲"application/json"。雖然這是一個值mimeType值,但$.ajax函數需要以下預定義值之一:xml, json, script, or htmlthe relevant page of the documentation中所列。

嘗試爲您的來電$.ajax是這個樣子:

$.ajax({ 
     type: "POST", 
     dataType: "json", 
     url: "php/parseFunctions.php", 
     data: {data:queryObj}, 
     success:{...}, 
     complete:{...}, 
     error:{...} 
}); 
+0

哇,我怎麼也想不到的是到了那裏,我覺得愚蠢的沒有看到它,謝謝! – DelightedD0D

+1

你不應該感覺不好!這是一種非常有效的字符串類型,可以查看Web應用程序 - 它不一定會跳出來,因爲有些問題。樂意效勞!快樂的編碼! – Lix