最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery AJAX catch status code errors - Stack Overflow

programmeradmin0浏览0评论

I am trying to catch specific response errors using jQuery's $.ajax.

When there is an 500 or 404 error code, instead of running the status code functions, it runs the error function and I get an alert box instead of what is supposed to happen

Here is what my code looks like

// get page data
getPageData: function(url, callback) {

    url = ajaxLoader.getURL(url);

    $.ajax({
        url: url,
        type: 'get',
        data: {_ajax_loader: 1},
        error: function(xhr, status) {
            alert('There was a problem loading that page. You may need to refresh.');
        },
        statusCode: {
                404: function(response) {
                    ajaxLoader.fetchPage('/missing');
                },
                500: function(response) {
                    ajaxLoader.fetchPage('/error'); 
                }
            }           
    }).done(callback);
},

I am trying to catch specific response errors using jQuery's $.ajax.

When there is an 500 or 404 error code, instead of running the status code functions, it runs the error function and I get an alert box instead of what is supposed to happen

Here is what my code looks like

// get page data
getPageData: function(url, callback) {

    url = ajaxLoader.getURL(url);

    $.ajax({
        url: url,
        type: 'get',
        data: {_ajax_loader: 1},
        error: function(xhr, status) {
            alert('There was a problem loading that page. You may need to refresh.');
        },
        statusCode: {
                404: function(response) {
                    ajaxLoader.fetchPage('/missing');
                },
                500: function(response) {
                    ajaxLoader.fetchPage('/error'); 
                }
            }           
    }).done(callback);
},
Share Improve this question asked Jan 16, 2017 at 19:37 BenBen 5,7779 gold badges36 silver badges50 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 9

This is by design. error is executed when an error is returned by the server. Further, the functions defined in statusCode are also called as well. The same applies to plete and success handlers.

You could modify your error handler not to run when the error code is already defined in statusCode.

$.ajax({
    url: '/echo',
    type: 'get',
    success: function() {
        console.log('ajax.success');
    },
    error: function(xhr, status) {
        // check if xhr.status is defined in $.ajax.statusCode
        // if true, return false to stop this function
        if (typeof this.statusCode[xhr.status] != 'undefined') {
            return false;
        }
        // else continue
        console.log('ajax.error');
    },
    statusCode: {
        404: function(response) {
            console.log('ajax.statusCode: 404');
        },
        500: function(response) {
            console.log('ajax.statusCode: 500');
        }
    }
});

Demo

The issue is that you are using the error callback in addition to the statusCode object. The error callback is triggered when any type of error occurs, including HTTP errors like 404 or 500.

To fix this, you need to remove the error callback and only use the statusCode object.

Here is the corrected code:

// get page data getPageData: function(url, callback) {

url = ajaxLoader.getURL(url);

$.ajax({
    url: url,
    type: 'get',
    data: {_ajax_loader: 1},
    statusCode: {
            404: function(response) {
                ajaxLoader.fetchPage('/missing');
            },
            500: function(response) {
                ajaxLoader.fetchPage('/error'); 
            }
        }           
}).done(callback);

},

This way, only the appropriate function will be called when a 404 or 500 status code is returned, and not the error callback.

$.ajax has success and error functions, so you can handle it with jqXHR defined for both.

On success:

success: function(data, status, jqXHR) {
        switch(jqXHR.status){
           case 200:
                    //status ok
                    break;
           case 206:
                    //Partial Content
                    //awesome code for handle it
                    break;

        }
    }

On error:

error: function(jqXHR, status, errorThrown) {
        switch(jqXHR.status){
           case 400:
                    //Bad Request
                    //awesome code for handle it
                    break;
           case 404:
                    //Not Found
                    //awesome code for handle it
                    break;

        }
    }

Here all status codes

It will execute both the error and appropriate StatusCode function.

The only issue with your code is that in your StatusCode functions, you have the argument of response (which I assume is the argument for the success function), when it should match the error function arguments, as follows:

// get page data
getPageData: function(url, callback) {

    url = ajaxLoader.getURL(url);

    $.ajax({
        url: url,
        type: 'get',
        data: {_ajax_loader: 1},
        error: function(xhr, status) {
            alert('There was a problem loading that page. You may need to refresh.');
        },
        statusCode: {
            404: function(xhr, status) {
                ajaxLoader.fetchPage('/missing');
            },
            500: function(xhr, status) {
                ajaxLoader.fetchPage('/error'); 
            }
        }           
    }).done(callback);
},

With this, if a 404 or 500 is received, both the error function and the 404/500 function will execute. If you instead desire to have only the 404/500 function execute, and the error function will only execute if the returned status is not 404 or 500, you can do this as follows:

// get page data
getPageData: function(url, callback) {

    url = ajaxLoader.getURL(url);

    $.ajax({
        url: url,
        type: 'get',
        data: {_ajax_loader: 1},
        error: function(jqXHR, status) {
            switch (jqXHR.status) {
                case 404:
                    ajaxLoader.fetchPage('/missing');
                    break;
                case 500:
                    ajaxLoader.fetchPage('/error');
                    break;
                default:
                    alert('There was a problem loading that page. You may need to refresh.');
            }
        }         
    }).done(callback);
},
发布评论

评论列表(0)

  1. 暂无评论