1

我不知道如何处理 $.post() 上的 404 错误?

$.post(url, data, function(returnedData) {

它只能处理成功数据,但我也想处理 404 错误。我知道如何用 ajax 来做,但不知道这个功能,请帮忙。

    function returnData(url,data,type){
        $.post(url, data, function(returnedData) {
        if(type == "contacts")
        {   
        ko.applyBindings(new ContactsViewModel(returnedData,"#KnockOutContacts",url,data),$("#KnockOutContacts")[0]);   
        ko.applyBindings(new ContactsViewModel(returnedData,"#ContactDetails",url,data),$("#ContactDetails")[0]);   
        }
        else if(type == "logs")
        {
        alert(returnedData);
        alert(1);
        ko.applyBindings(new LogsViewModel(returnedData,url,data),$("#KnockOutLogs")[0]);   
        }
        else if(type == "sms")
        {
            ko.applyBindings(new SmsViewModel(returnedData,"#KnockOutSmsData",url,data),$("#KnockOutSmsData")[0]);  
            ko.applyBindings(new SmsViewModel(returnedData,"#KnockOutSms",url,data),$("#KnockOutSms")[0]);  
        }
        else if(type == "calendar")
        {
        ko.applyBindings(new CalendarViewModel(returnedData,"#KnockOutCalendar",url,data),$("#KnockOutCalendar")[0]);   
        }
        else if(type == "search")
        {
        ko.applyBindings(new SearchViewModel(returnedData,"#searchbox",url,data),$("#searchbox")[0]);   
        }
        else if(type == "location")
        {
        ko.applyBindings(new LocationViewModel(returnedData,"#KnockOutMaps",url,data),$("#KnockOutMaps")[0]);   
        }
        else if(type == "photos")
        {
        ko.applyBindings(new PhotosViewModel(returnedData,"#photogallary",url,data),$("#photogallary")[0]); 
        ko.applyBindings(new PhotosViewModel(returnedData,"#PhotosDown",url,data),$("#PhotosDown")[0]); 
        }
    });
}

我在获取数据时基本上应用绑定,但是当我没有获取数据时,它不会进入成功函数,这会破坏我的 js。

4

2 回答 2

9

在此处阅读有关statusCode回调的信息

$.ajax({
    url: "/page.htm",
    type: "POST",
    statusCode: {
        404: function() {
          alert("page not found");
        }
    }
})

编辑。

也可以接受$.post

$.post(url, data, function(returnedData) {
    //callback
}).fail(function(jqXHR, textStatus, errorThrown){
    if(jqXHR.status == 404) {

    }
});
于 2013-02-18T10:41:31.747 回答
3

您可以使用全局错误处理程序:

$(document).ajaxError(function(e, xhr, settings, exception) {

});
于 2013-02-18T10:41:12.090 回答