2011-05-14 41 views
0

我一直在尝试循环播放ajax请求,但它仅在最后一个循环中执行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;  
     } 
+0

此外,如果你能解释一下你正在尝试做的事情 - 你想找出是否有任何三页包含此元素?你想打开页面并行还是一个接一个? etc – serg 2011-05-14 20:33:08

+0

@serg嗨,我想保存关键字的元素存在。保存一个单独的数组或其他东西。可能? – RaviTeja 2011-05-15 02:39:11

+0

您将有一个找到的关键字的索引,所以在'result()'方法中,您可以通过'keywords [i]'获得找到的关键字。 – serg 2011-05-15 02:42:29

回答

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 
}