所以我想做的就是有条件地从.fail
方法中调用.success
方法,怎么做?
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { ajaxCall.fail(); return; }
alert("success");
})
.fail(function () {
alert("fail");
});
答案 0 :(得分:2)
$.ajax
返回承诺,因此您无法直接执行此承诺。你的最佳镜头是:
var fail = function () {
alert("fail");
};
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { fail(); return; }
alert("success");
})
.fail(fail);
答案 1 :(得分:0)
您可以简单地拨打this.fail();
,如下所示: -
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail")
{
this.fail();
return;
}
alert("success");
})
.fail(function () {
alert("fail");
});
有关更多信息: -
http://www.youlikeprogramming.com/2013/07/jqueryajax-conditionally-call-error-method-fro-success/
答案 2 :(得分:0)
只需使用"这个"实际调用ajax调用的任何其他方法的关键字,我已经为错误方法做了一个示例。
$.ajax({
url: 'url',
dataType: 'json',
contentType: 'application/json; charset=utf-8;',
type: 'GET',
success: function (dataReturn) {
this.error('error called explicitly');
},
error: function (errorMessage) {
if(errorMessage.ResponseText) // or directly compare as errorMessage !== "error called explicitly" if u send the same message elsewhere
//actual error code
else
alert(errorMessage);
}
});
希望这有助于:)