2010-07-08 64 views
0

無效網址不給錯誤,我注意到,當我到get()提供了一個無效的網址我沒有得到任何錯誤jQuery的get()方法時提供

$.get(nextHref, function(data, status, xhr) { 
    alert(status); 
    if (status == "error") { 
    alert("an error has occured: " + xhr.status + " " + xhr.statusText); 
    } 

alert(status); NV甚至可以運行時,我提供了一個無效的網址

回答

3

$.get()回調是一個成功函數,所以這絕不會出現錯誤,您可以使用$.ajax()作爲完整版本,或者創建一個全局錯誤事件處理程序,無論哪一個更合適。

如果你想使用$.ajax(),使用error回調,像這樣:

$.ajax({ 
    url: nextHref, 
    success: function(data) { 
    //do something with good data, what comes after your if statement currently 
    }, 
    error: function(xhr, status, error) { 
    alert("an error has occured: " + xhr.status + " " + xhr.statusText); 
    } 
}); 

或者使用全局事件處理$().ajaxError()這樣的:

$(document).ajaxError(function(e, xhr) { 
    alert("an error has occured: " + xhr.status + " " + xhr.statusText); 
}); 

或者,使用$.ajaxSetup()添加一個error所有請求的處理程序,如下所示:

$.ajaxSetup({ 
    error: function(xhr, status, error) { 
    alert("an error has occured: " + xhr.status + " " + xhr.statusText); 
    } 
}); 
3

API頁:

如果有jQuery.get()請求返回錯誤代碼,它會悄悄地失敗,除非劇本也被稱爲全球.aja xError()方法。

閱讀關於ajaxError here

基本上你需要做的是從那裏連接ajaxError一些項目,以及處理錯誤:

我們可以將我們的事件處理程序的任何元素:

$('.log').ajaxError(function() { 
    $(this).text('Triggered ajaxError handler.'); 
}); 

現在,我們可以使用任何jQuery方法發出Ajax請求:

$('.trigger').click(function() { 
    $('.result').load('ajax/missing.html'); 
}); 
0

如果您希望發現錯誤,請使用:

$.ajax({ 
    url : url, 
    success : function(result) { 
     //doSomething 
    }, 
    error : function(request, status, error) { 
     if(status == 'parsererror' || status == 'error') { 
     //doSomething 
     } 
    } 
});