简体   繁体   中英

How do I handle a 500 error with JSON javascript post?

There's a few different ways to write a JSON block but the method I prefer looks something like this:

$.post('/controller', { variable : variable }, function(data){
    if(data.status == '304') {
        // No changes over the previous
    } else if(data.status == 'ok') {
        // All is good, continue on and append whatever...
    } else if(data.status == 500) {
        // Server error, brace yourself - winter is coming!
    }
}, "json");

I've tried the last condition to be else if data.status == null, 500, false, and just have it as an else statement (instead of else if) but still nothing. This tells me that because it's returning a 500 error and can't fetch any information at all, it won't even consider doing anything inside the brackets so there has to be an exception outside of it right or am I wrong?

How exactly do I get this to work without having to use something like

$.ajax({
    url : '/controller',
    type : 'POST',
    dataType : {
        lookup : JSON.stringify(lookup)
    },
    data : lookup,
    contentType : 'application/json; charset=utf-8',
    success: function (data) {
        // Stuff
    },
    error: function (xhr, ajaxOptions, thrownError) {
       // Stuff
    }
});

Thank you!

The third parameter to $.post() is called success , so the function is only being run on, well, success . 500 is an error status, so the function is not run.

Instead, you should be able to use the Deferred object returned from $.post() . This contains an always() method, which is run regardless of success or failure:

$.post('/controller', { variable : variable }, null, "json")
    .always(function(data, textStatus, jqXHR) {
        if(jqXHR.status == 304) {
            // No changes over the previous
        } else if(jqXHR.statusText == "OK") {
            // All is good, continue on and append whatever...
        } else if(jqXHR.status == 500) {
            // Server error, brace yourself - winter is coming!
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM