2011-05-14 43 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 
}