2011-02-19 14 views
21

我是一個JQuery n00b。我試圖用$ .get()編寫一個非常簡單的代碼。 official documentation

If a request with jQuery.get() returns an error code, it will fail silently 
unless the script has also called the global .ajaxError() method or. 

As of jQuery 1.5, the .error() method of the jqXHR object 
returned by jQuery.get() is also available for error handling.

所以,如果一切順利,我的成功回調函數將被調用。但是,如果請求失敗,我想獲取HTTP代碼:404,502等,併爲用戶制定有意義的錯誤消息。

但是,由於這是一個異步調用,我可以想象,我可能有幾個優秀的。 .ajaxError()如何知道它對應哪個請求?也許最好使用jQuery.get()返回的jqXHR對象的.error()方法?

有人可以prvode一個非常簡單的代碼示例?也許成功的程序調用警報(「頁面找到」)和故障例行檢查404並執行警報(「找不到網頁」)


更新:下面的頁面是非常有用的... http://api.jquery.com/jQuery.get/

回答

48

你說的沒錯,你可以使用jQuery 1.5的新jqXHR到錯誤處理程序分配給$.get()請求。這是你如何做到這一點:

var request = $.get('/path/to/resource.ext'); 

request.success(function(result) { 
    console.log(result); 
}); 

request.error(function(jqXHR, textStatus, errorThrown) { 
    if (textStatus == 'timeout') 
    console.log('The server is not responding'); 

    if (textStatus == 'error') 
    console.log(errorThrown); 

    // Etc 
}); 

你也可以連接處理程序,直接到電話:

$.get('/path/to/resource.ext') 
    .success(function(result) { }) 
    .error(function(jqXHR, textStatus, errorThrown) { }); 

我更喜歡前者,以保持較少的糾結的代碼,但兩者是等價的。

14

.get()只是.ajax()的同義詞,其中包含許多選項。使用ajax()可以獲得全部選項,包括error回調。

$.ajax({ 
type: "GET", 
url: "test.htm", 
error: function(xhr, statusText) { alert("Error: "+statusText); }, 
success: function(msg){ alert("Success: " + msg); } 
} 
); 
+0

+ 1That顯示了一個的n00b我,我不知道。我會嘗試一下並回復你。謝謝。 – Mawg 2011-02-19 23:28:48

+0

順便說一句,我如何將CGI參數傳遞給URL。例如google.com?serach="pizza「 – Mawg 2011-02-20 00:54:23

1

從jQuery 3.0開始.success().error()已折舊。
您可以使用.done().fail()代替

$.get(url) 
    .done(function(data, textStatus, jqXHR) { 
     console.log(data); 
    }) 
    .fail(function(jqXHR, textStatus, errorThrown) { 
     console.log(jqXHR); 
     console.log(textStatus); 
     console.log(errorThrown); 
    }); 

來源:https://api.jquery.com/jQuery.ajax/