[英]jQuery AJAX request events - done,fail,success
我有這樣的代碼
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
}
});
失敗和完成只是示例,如果在內部使用,則complete也不起作用。 但是在外面像這樣使用它:
ajaxrequest.complete(f(){});
工作得很好...我知道而不是完成我應該利用成功,但這不是我的意思。 這是怎么回事?
如果要使用第二個選項,則需要使用成功,而錯誤是需要使用的方法
這是無承諾的ajax請求的示例,您將獲得成功和錯誤函數作為參數
$.ajax({url:"demo_test.txt"
,error : function (xhr,status,error)
{ //alert error}
,success:function(result){
$("#div1").html(result);
}});
在第一個操作中,您使用的是由ajax requst返回的promise對象,這是您完成方法和fail方法的原因。
這是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 );
});
棄用通知:從jQuery 3.0開始,刪除了jqXHR.success(),jqXHR.error()和jqXHR.complete()回調。 您可以改用jqXHR.done(),jqXHR.fail()和jqXHR.always()。
您可以簡單地使用$ .post代替$ .ajax和json作為第四個參數。
$.post("n3_vaje_api.php", {action : "read"}, function(response) {
// Do something with the request
}, 'json')
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.