如何使用JSON javascript post处理500错误?
有几种不同的方法可以编写JSON块,但我更喜欢的方法如下:如何使用JSON javascript post处理500错误?,javascript,json,ajax,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 wh
$.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");
我尝试将最后一个条件设置为else if 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
}
});
谢谢大家! 的第三个参数称为success
,因此该函数只在success上运行<代码>500为错误状态,因此该功能未运行
相反,您应该能够使用从$.post()
返回的对象。它包含一个方法,无论成功与否都将运行该方法:
$.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!
}
});
console.log(data.status)
为您提供了什么?(显然放在“如果其他”语句之前)非常感谢您的明确解释!已解决并理解问题:)