我使用 JQuery 和 $.when 方法向服务器发出请求。
$.when(ajaxRequest(param)).done(function(response){
console.log(responseData);
});
我的 ajax 函数如下所示:
function ajaxRequest(param){
var requestedData;
return $.ajax({
type: 'POST',
url: myurl,
data: {
setParam:param
},
error: function(data){
console.log(data);
return(data);
}
});
}
如果服务器返回 200 OK,一切正常。但如果出现错误,服务器会返回 500。我如何将响应主体返回给调用方法?
errorbody 在 ajaxRequest 方法上用 console.log 打印,但它没有返回给调用方法?
最佳答案
问题 $.when()
中给出的 js
不是必需的,因为 $.ajax()
返回一个 jQuery promise 对象。 var requestedData;
未设置为值,将在 .done()
处为 undefined
;使用 .then()
或 .done()
中可用的 response
作为返回数据; .then()
处理成功和错误响应
function ajaxRequest(param){
return $.ajax({
type: 'POST',
url: myurl,
data: {
setParam:param
}
});
}
ajaxRequest(param)
.then(function(response){
console.log(response);
return response
}
// handle errors at second function of `.then()`
, function err(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
return errorThrown;
});
关于javascript - JQuery ajax stoppen in $.when 服务器返回 500 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36175033/