2014-04-01 132 views
0

我正在向我的服務器發送一個ajax調用,其中參數是「general」或任何文本,對於一個搜索查詢,爲什麼它總是給出錯誤。迴應是在JSON,我已經提到過,下面的代碼的任何問題?任何幫助將高度讚賞Jquery Ajax請求出錯,它總是執行錯誤塊

$.ajax({ 
    url : "${kb_endpoint_url}", 
    dataType : 'json', 
    data : { search_query : queryValue }, // queryValue = general 
    success : function(data) { 
      console.log("success"); 
    }, 

    error: function (xhr, status, error) { 
     console.log(" xhr.responseText: " + xhr.responseText + " //status: " + status + " //Error: "+error); 

    } 

此打印:xhr.responseText: undefined //status: SyntaxError: JSON.parse: unexpected character //Error: undefined

編輯:我試圖改變類型的應用程序/ JSON和現在控制檯打印

xhr.responseText:未定義//狀態:沒有從文本到應用程序/ json的轉換//錯誤:undefined

+1

根據錯誤,你的反應是不是在JSON或您的JSON文件被破壞。 –

+0

這是一個網址? –

+0

@AmitJoki - 是的,它存儲在一個freemarker變量 – Chanakya

回答

-1

如果您發表評論dataType : 'json',您的ajax正常運行。您的回覆不是JSON格式。

$.ajax({ 
     url : "${kb_endpoint_url}", 
     dataType : 'json', 
     type : 'post', 
     data : { search_query : queryValue }, // queryValue = general 
     success : function(data) { 
       console.log("success"); 
     }, 

     error: function (xhr, status, error) { 
      console.log(" xhr.responseText: " + xhr.responseText + " //status: " + status + " //Error: "+error); 

     } 
}); 

另一個文件(提到URL)

<?php 

echo json_encode($_POST); 

?> 
0
xhr.responseText: undefined //status: SyntaxError: JSON.parse: unexpected character //Error: undefined 

我想;這個錯誤意味着從你的URL返回的響應不是JSON,試圖解析它的錯誤是這樣的。

要不是看在你的網絡面板(容易),或調整您的錯誤處理程序,看看有什麼反應你的服務器實際上返回,通過查看responseText

+0

奇怪的部分是responseText返回正確的響應 – Chanakya

0

如果服務器返回文本undefined,這不是有效的JSON並且不能被解析。
只有null在JSON格式中有效,所以試圖解析undefined會出現此錯誤。

爲例子:

JSON.parse("undefined"); // Throws an error, "Unexpected token u" 
JSON.parse("null");  // Returns null