2010-06-16 25 views
0

我們有用於每個.item腳本:jQuery的抓IMG

$(".item").each(function(){ 
    item_link = "http://..."; 
    block = $('.block', this); 
    $.get(item_link, function(data) { 
     var src = $('img.slide', data).attr('src'); 
     block.html(src); 
    }); 
}); 

item_link變量是每個查詢各式獨特。

可能有100 .item或更多。

問題是 - 服務器在同一時間有連接限制,爲什麼一些.item得到var src,有些沒有。

最好的解決方案是同時只使用一個.get。我認爲應該有一些計數器,如果.get完成 - 它給出消息「我完成了,你可以開始」到下一個.get等等。

如何做到這一點?

謝謝。

+0

這不應該發生。你有任何錯誤? – SLaks 2010-06-16 15:41:09

+0

我得到「503服務暫時不可用」 – Happy 2010-06-16 16:06:33

回答

4

瀏覽器應自動排隊請求,並在前兩次完成之後發送每個請求。

因此,您當前的代碼應該可以正常工作。
檢查Fiddler或Firebug並查看請求是否失敗。

編輯

你戰鬥的服務器油門,而不是瀏覽器的連接限制。

您需要維護一個發送請求的函數數組,然後調用AJAX回調中的下一個函數。

例如:

var requests = []; 
function runFirstRequest() { 
    if (requests.length > 0) 
     requests.splice(0, 1)(); //Pop the first function from the queue and execute it 
} 


$(".item").each(function(){ 
    item_link = "http://..."; 
    block = $('.block', this); 

    requests.push(function() { 
     $.get(item_link, function(data) { 
      var src = $('img.slide', data).attr('src'); 
      block.html(src); 

      runFirstRequest(); //Send the next request 
     }); 
    }); 
}); 

runFirstRequest(); 

然而,讓數百名AJAX請求是一個壞主意。
您應該修改您的代碼以發送一個AJAX請求,以返回您需要的所有數據。
這將解決您的問題,並使頁面更快。

+0

+1使得所有的請求都成爲單一請求 – Jiaaro 2010-06-16 15:46:15

+0

有很多GET請求,其中大部分給出「503服務暫時不可用」 – Happy 2010-06-16 16:03:20

+0

不起作用,什麼也沒有顯示 – Happy 2010-06-16 16:26:24

2

你應該把他們都在一個大的請求,讓服務器遍歷它們來代替:

items_ids = []; 
$(".item").each(function(){ 
    item_ids.push(some_identifier_for_the_item); 
}); 

get_item_data_link = "http://..."; 
$.get(item_link, {"items": item_ids}, function(data) { 
    ... loop through the results and stick them in the page 
}); 

PS - 如果你仍然在發出請求隊列使用PUSH,POP,移設和不印字

先進先出隊列:

queue = []; 

// add 3 items to the queue 
queue.push('item1'); 
queue.push('item2'); 
queue.push('item3'); 

// get the oldest item off the queue (ie. the first item 
// added is the first item handled) 

queue.shift(); // "item1" 

後進先出隊列:

queue = []; 

// add 3 items to the queue 
queue.push('item1'); 
queue.push('item2'); 
queue.push('item3'); 

// get the newest item off the queue (ie. the last item 
// added is the first item handled) 

queue.pop(); // "item3"