2011-08-09 43 views
5

我的代碼是:如何調試jQuery Ajax請求?

var test = "it isn't working"; 
var response = $.ajax({ 
    type: 'GET', 
    url: 'jquerydemo.php', //This is in the same site as the page calling this request, so it's not a same-domain error. 
    success: function(){ 
      test = "it's working"; 
     }, 
    error: function(){ 
      alert("Error detected"); 
     } 
}).responseText; 
alert(test); 

我測試的狀態碼,它出來的200和誤差函數從未熄滅,但同樣沒有成功的功能。就像我在評論中所說的那樣,這不是一個同源的政策錯誤。它只是說「它不工作」。這裏發生了什麼?

回答

5

您的ajax調用是異步的。當最後的警報運行時,它還沒有完成。在成功功能中添加一個實際的警報,你應該看到你的結果。

請記住,使ajax調用剛啓動異步ajax調用,然後代碼的其餘部分繼續運行。在您發佈的代碼示例中,這意味着您的alert(test)調用在ajax調用完成之前立即運行。

您只能從成功處理程序本身檢查ajax調用的結果。

var test = "it isn't working"; 
var response = $.ajax({ 
    type: 'GET', 
    url: 'jquerydemo.php', //This is in the same site as the page calling this request, so it's not a same-domain error. 
    success: function(){ 
      alert("it's working"); // put this here and you will see it 
            // if the ajax call is successful 
     }, 
    error: function(){ 
      alert("Error detected"); 
     } 
}).responseText; 
+0

您也可以選擇添加'異步的選項:TRUE'你在你的'ajax'呼叫傳遞的設置,但要記住,這將停止執行的是整個線程在你的腳本中,直到請求返回。 – dfreeman

+0

@SchiefGelaufen - 我假設你的意思是'async:false'。將ajax調用轉換爲同步調用確實是一種選擇,但由於它在ajax調用期間鎖定了整個網頁,因此它幾乎不是最好的設計選擇。使用'async:true'編寫代碼會更加複雜,但可以提供更好的用戶體驗。 – jfriend00

+0

哎呦,我這個傻傻的錯字。是的,'async:false'。做一個同步ajax請求並不一定是正確的(至少,有很多情況下它不會),但在你的成功中放置任何依賴於響應的邏輯當然被認爲是更好的做法回電話。 – dfreeman

0

你可以把它像

var response = $.ajax({ 
    type: 'GET', 
    url: 'jquerydemo.php', 
    success: function(){ 
      alert("it's working"); 
     }, 
    error: function(){ 
      alert("Error detected"); 
     } 
}).responseText; 

這將工作....

1

此舉警報(測試)從一端插入Ajax調用成功功能。 如果它提示它意味着代碼正在工作,否則它不是。你只能在成功返回時調試ajax調用。

var test = "it isn't working"; 
var response = $.ajax({ 
    type: 'GET', 
    url: 'jquerydemo.php', 
    success: function(){ 
      test = "it's working"; 
      alert(test); //It will alert when you ajax call returns successfully. 
     }, 
    error: function(){ 
      alert("Error detected"); 
     } 
}).responseText; 

希望這會有所幫助。

2

要調試這些類型的東西,我需要find Firebug一個不可或缺的工具。它會向你顯示服務器的確切響應(5​​00錯誤,553錯誤,你有什麼)。您可以在您的Javascript代碼中放置斷點並逐步進行調試。 Firebug適用於Firefox。

對於IE,您可以使用類似於Firebug的開發工具功能,特別是在IE9上,它比以前版本的IE7或IE8開發工具更成熟。

+0

對於IE,還有Firebug Lite - http://getfirebug.com/firebuglite –

+0

你也可以在Chrome中按下CTRL-SHIFT-J – pilavdzice

12

試試這個:

error: function(jqXHR, textStatus, errorThrown) { 
     console.log(JSON.stringify(jqXHR)); 
     console.log("AJAX error: " + textStatus + ' : ' + errorThrown); 
}