我有这样的数组urls = ['url1','url2','url3'];
我如何跟踪数组索引,所以在每次Ajax
调用时我都可以删除一个元素。
这是我正在尝试的事情
var my_delay = 2000;
var urls = ['url1','url2','url3'];
$(function() {
callAjax();
});
function callAjax() {
/*$.ajax({
// my ajax params ..............
success: function(data){
if(urls.length != 0){
console.log('must be called only 3 times');
setTimeout(callAjax, my_delay);
urls.shift();
}
}
}); */
console.log('must be called only 3 times');
console.log('in real situation i will going to use above commented ajax code');
if(urls.length != 0){ // stop here but you are not stoppping why?
setTimeout(callAjax, my_delay);
urls.shift();
} // end of if
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
&#13;
问题我希望在urls[]
中没有元素时停止ajax调用请注意ajax
将调用php page
方案我也希望跟踪array index
答案 0 :(得分:1)
使用全局变量和递归函数
var i = 0;
callAjax(urls[i]);
function callAjax(url) {
$.ajax({
url:url,
success:function() {
if (i< urls.length)
i++;
callAjax(urls[i]);
}
});
}
答案 1 :(得分:1)
试试吧 $(function(){
var urls = ['url1','url2','url3'],
function callAjax(url) {
alert(url);
}
// for each array element call function callAjax
$.each( urls, function( i, url ) {
callAjax(url);
});
});
答案 2 :(得分:-2)
也许您需要这样:$.when()
1.5
jquery
http://devdocs.io/jquery/jquery.when
这样,在所有Ajax完成之后,你将得到array
结果保持之前的轨迹。