有几种不同的写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语句(而不是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
}
});
谢谢!
最佳答案
$.post()
的第三个参数称为success
,因此该函数只能成功运行。 500
是错误状态,因此该功能未运行。
相反,您应该能够使用从Deferred
返回的$.post()
对象。它包含一个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!
}
});
关于javascript - 如何处理JSON JavaScript帖子500错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35509277/