我有这样的代码
var ajaxrequest = $.ajax({
type: "POST",
dataType: "json",
url: "xy.php",
data: {
action : "read"
}
}).fail(function(){
//something to do when ajaxreq fails
}).done(function(data){
//something to do when ajaxreq is done
});
运行没有问题。我的问题是为什么这不起作用:
var ajaxrequest = $.ajax({
type: "POST",
dataType: "json",
url: "n3_vaje_api.php", //Relative or absolute path to response.php file
data: {
action : "read",
},
fail:function(){
//something to do when ajaxreq fails
},
done:function(data){
//something to do when ajaxreq is done
}
});
Fail 和done 只是示例,在内部使用complete 也不起作用。但在外面使用它就像:
ajaxrequest.complete(f(){});
工作得很好...我知道我应该使用 success 而不是完成,但这不是我的观点。 这是怎么回事?
最佳答案
如果你想使用第二个选项,你需要使用 success 和 error 是你需要使用的方法
这是没有 promise 的 ajax 请求的示例,您将成功和错误函数作为参数
$.ajax({url:"demo_test.txt"
,error : function (xhr,status,error)
{ //alert error}
,success:function(result){
$("#div1").html(result);
}});
<小时/>
在第一个选项中,您使用的是 ajax 请求返回的 Promise 对象,这就是您完成任务并失败方法的原因。
这是 Promise 对象的示例,在下面的示例中请求是 Promise 对象
var request = $.ajax({
url: "script.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
关于javascript - jQuery AJAX 请求事件 - 完成、失败、成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28044436/