[英]Execute callback at end of for-loop XMLHttpRequest
此代碼循環瀏覽多個網頁,在每個頁面上查找鏈接,然后將這些鏈接放入名為linksArray
的數組中。 我試圖在for循環在其最后一次迭代時(當x = 45時)和jQuery find().each
執行一次回調find().each
都在最后一頁的所有鏈接中完成搜索。
由於某些原因,我沒有從最后一頁( http://fakeURL.com/45 )獲得鏈接。 似乎回調函數在for循環遍歷每個網頁之前執行。 為什么會發生這種情況,我該如何解決?
function linkSearch(callback)
{
for(i = 0; i <= 45; i += 1)
{
ajaxCall(i);
}
var i;
var linksArray = [];
function ajaxCall (x)
{
var xhrs = new XMLHttpRequest();
xhrs.open("get", 'http://fakeURL.com/' + x, true);
xhrs.onload = function()
{
var doc = xhrs.response;
var len = $(doc).length; //will be used in telling when .each has gotten to the end of a page
$(doc).find("a[href^='http://linksFromEachPage.com/links']").each(function(index, element)
{
//below is how I'm trying to callback the linksArray when the for-loop is on its last iteration and .each has finished on the last page
thisVal = $(this).val();
if (x == 45)
{
if(parseInt(thisVal) != 0)
{
if (index == len - 1)
{
if($(doc).ajaxComplete)
{
callback(linksArray);
}
}
}
}
var url = $(this).attr('href');
linksArray[x] = url;
});
}
xhrs.responseType = 'document';
xhrs.send();
}
}
//and below is where the callback is called
linkSearch(function(theArray)
{
console.log(theArray);
});
由於您的問題是用jQuery標記的,因此這是使用jQuery進行ajax調用的代碼版本,並且jQuery承諾會跟蹤它們何時完成。
function linkSearch(callback) {
var i, promises = [];
for (i = 0; i <= 45; i++) {
promises.push(
$.get({url:'http://fakeURL.com/' + i, dataType:'xml'})
);
}
$.when.apply($, promises).then(function() {
var linksArray = [];
// process all results here
for (i = 0; i < arguments.length; i++){
$(arguments[i][0])
.find("a[href^='http://linksFromEachPage.com/links']")
.each(function(index, element) {
var url = $(this).attr('href');
linksArray.push(url);
});
}
callback(linksArray);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.