循环使用chrome扩展中的ajax请求,无法正常工作

时间:2011-05-14 20:19:54

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

我正在尝试循环遍历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;    
        }

1 个答案:

答案 0 :(得分: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
}