2013-01-09 40 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

相关问题