【问题标题】:Looping over ajax requests in a chrome extension, not working在chrome扩展中循环ajax请求,不起作用
【发布时间】:2011-05-14 20:19:54
【问题描述】:

我一直在尝试循环遍历 ajax 请求,但它只为最后一个循环执行 ajax 操作。

while(i<3){
var query = site_url+keywords[i]+'"' ;
         $.ajax({
            url: query,
            type: "GET",
            dataType: "html"
success: function(html) {
var el = $(html).find("#tagID");
                    if(el.length) {
                        console.log("Element  exists");  
                        var cont = 1;

                    }
else{
console.log("Element  doesnt exist");
 var cont = 0;
}
}
});
        console.log(cont);

        i=i+1;    
        }

【问题讨论】:

  • 另外,如果你能解释一下你想要做什么 - 你想知道这三个页面中的任何一个是否包含这个元素吗?您是要并行打开页面还是一个接一个地打开页面?等
  • @serg 嗨,我想保存元素存在的关键字。保存一个单独的数组或其他东西。可能吗?
  • 您将拥有已找到关键字的索引,因此在result() 方法中您可以使用keywords[i] 获取找到的关键字。

标签: ajax google-chrome jquery google-chrome-extension


【解决方案1】:

类似的东西:

processKeyword(0);

function processKeyword(i) {
    if(i < keywords.length) {
        var query = site_url+keywords[i]+'"' ;
        $.ajax({
            url: query,
            type: "GET",
            dataType: "html"
            success: function(html) {
                var el = $(html).find("#tagID");
                if(el.length) {
                    //found, stop processing
                    result(i);
                } else{
                    //not found, process next
                    processKeyword(i + 1);
                }
            }
        });

    } else {
        //all processed, nothing found
        result(-1);
    }

}

function result(i) {
    //i contains keyword index if was found, -1 otherwise
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多