2013-01-09 39 views
0

我有這樣的代碼。環路長度是磨碎機大於100如何停止循環,直到響應得到jQuery的?

$('.check_box_ping:checked').each(function(i, obj) { 
    $.post(
     "mass_ping.php", 
     "ping", 
     function(response) { 
     } 
    ); 
}); 

現在同時發生100個$.post()呼叫。我想在從服務器獲得之前$.post()的響應之後,按順序執行每個$.post()

+0

你真的不應該同時或不同時發送100個Ajax請求。 – gdoron

+0

每個請求觸發10個捲曲在服務器中。所以需要30秒。如果我一次發送100個數據,則需要100 * 30s。這將掛起我的服務器 –

+1

聽起來像你做錯了事情。非常錯誤。 – gdoron

回答

2

暫停你的循環爲每一個是使後同步通常是一個非常糟糕的用戶體驗的唯一方式(它掛起瀏覽器) 。

我的建議,而不是爲你調整你的循環讓你從以前的帖子的完成做下一次迭代:

(function() { 

    var checked = $('.check_box_ping:checked'); 
    var index = 0; 

    function next() { 
     if (index < checked.length) { 
      var item = checked.eq(index++); 
      // use item here for your post 
      $.post({...}, function(response) { 
       // do your normal handling of the response here 
       ... 
       // now kick off the next iteration of the loop 
       next(); 
      }); 
     } 
    } 
    next(); 

})(); 
1

你可以做兩件事情

  1. 更改您的代碼,以便您撥打您的第一篇文章的返回功能的下一個post。這將需要在您的當前循環中進行一些更改,但會使所有內容順利運行。
  2. 更快但很骯髒,是讓帖子同步。你可以在這個問題中找到:how to make a jquery "$.post" request synchronous。我會反對這個建議,因爲它會在加載過程中削弱你的頁面。
+0

我會建議無所作爲以上。他應該在一個請求中發送所有數據。 – gdoron

+0

每個請求觸發10個捲曲在服務器中。所以需要30秒。如果我一次發送100個數據,則需要100 * 30s。這將掛起我的服務器 –

+0

要清楚:我同意@gdoron:這聽起來像你做事的方式在結構上是錯誤的,所以它可能會更好,使它不需要這些黑客。 – Nanne

6

隨着deferred object你可以鏈中的所有Ajax調用返回的一些鏈接pipe()方法裏面一個承諾(見下面的控制檯輸出)

標記和js

<body> 
    <input type="checkbox" checked /> 
    <input type="checkbox" checked /> 
    <input type="checkbox" checked /> 
    <input type="checkbox" checked /> 
</body> 

<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script> 
<script> 
function doRequest() { 
    return $.post("script.php").done(function(response) { 
     console.log('Loaded in %d seconds', response); 
    }); 
} 

$(document).ready(function(){ 

    var dfd = $.Deferred(), 
     chain = dfd; 

    $('input:checked').each(function() { 
     chain = chain.pipe(function() { 
      return doRequest().promise(); 
     }); 
    }); 

    chain.done(function() { 
     console.log('done') 
    }); 

    return dfd.resolve(); 
}); 
</script> 

腳本。 php

<?php 
    $seconds = rand(2, 5); 
    sleep($seconds); 
    header("Content-type: text/html"); 
    echo($seconds); 
?> 

Sleep()僅用於模擬響應的隨機延遲。在JavaScript控制檯,你應該看到這樣的事情:

output

相關問題