如何使用JSON javascript帖子处理500错误?

时间:2016-02-19 15:47:27

标签: javascript json ajax

有几种不同的方法来编写JSON块,但我喜欢的方法看起来像这样:

$.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");

如果data.status == null,500,false,我已尝试将最后一个条件作为else,并将其作为else语句(而不是if)但仍然没有。这告诉我,因为它返回500错误并且根本无法获取任何信息,所以它甚至不会考虑在括号内做任何事情,所以必须在它之外有一个例外或者我错了吗?

如何在不使用

之类的情况下使其工作
$.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
    }
});

谢谢!

1 个答案:

答案 0 :(得分:1)

$.post()的第三个参数称为success,因此该功能仅在成功上运行。 500是错误状态,因此该函数未运行。

相反,您应该能够使用从$.post()返回的Deferred对象。这包含always()方法,无论成功与否,都会运行该方法:

$.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!
        }
    });