[英]Multiple Ajax Calls using jQuery
我是jQuery的新手,我需要檢索多個ajax調用的狀態代碼。 對於每個ajax調用,我需要顯示兩個警報彈出消息之一:1)成功(如果狀態代碼為200)2)失敗(對於200狀態代碼以外的任何內容)
我能夠顯示成功警報彈出窗口,但不確定如何/在何處顯示失敗消息:
$(document).ready(function() {
$("#btnSubmit").click(function(){
for (var i = 8078; i < 8085; i++) {
jQuery.ajax({
'url': 'http://localhost:' + i + '/test/',
dataType : 'jsonp',
crossDomain:true,
async:false,
statusCode: {
200: function() {
alert('Success');
}
}
});
};
});
});
請讓我知道如何處理失敗情況。 另外,我不確定是否正確使用了For循環。 請指導。
您在$.ajax
具有稱為error
屬性。 您可以嘗試如下操作:
$("#btnSubmit").click(function(){
for (var i = 8078; i < 8085; i++) {
jQuery.ajax({
'url': 'http://localhost:' + i + '/test/',
dataType : 'jsonp',
crossDomain:true,
async:false,
statusCode: {
200: function() {
alert('Success');
},
error:function(data){
alert('Failed');
},
});
}
});
同樣,您有success
檢查success
響應
更新
您可以嘗試另一種方法來完成此操作,如下所示:
for (var i = 8078; i < 8085; i++) {
jQuery.ajax({
'url': 'http://localhost:' + i + '/test/',
dataType : 'jsonp',
crossDomain:true,
async:false,
})
.done( function( data ) {
// Handles successful responses only
})
.fail( function( reason ) {
// Handles errors only
console.debug( reason );
})
.always( function( data, textStatus, response ) {
// If you want to manually separate stuff
// response becomes errorThrown/reason OR jqXHR in case of success
})
.then( function( data, textStatus, response ) {
// In case your working with a deferred.promise, use this method
// Again, you'll have to manually separates success/error
});
}
我發現此鏈接表明有兩個選項可以管理錯誤和成功。 您可以執行以下操作:
jQuery.ajax({
'url': 'http://localhost:' + i + '/test/',
dataType : 'jsonp',
crossDomain:true,
async:false,
statusCode: {
200: function() {
alert('Success');
}
},
error: function(xhr,status,error) {
alert('error!');
}
});
async:false,
success: function(data,textStatus,xhr){
// handle success
},
error: function(xhr,textStatus,error){
// handle error
},..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.