2010-10-13 165 views
5

嗨,我有一个很大的问题,一直在困扰着我很长一段时间,大多数时候我已经能够避免它,但现在没有其他方式。下面是一个函数,执行时会为每个选中的框发送一个post请求。我需要它等到$ .each完成刷新页面。我已经在每个回调函数中使用location.reload进行了测试。在10个选定的盒子中,只有7-8个在$ .each回调中重新加载,如果在$ .each(仍在.click中)之后移动,则处理3-4个。我需要它以某种方式等待$ .each完成并刷新页面。有没有办法做到这一点?

$('button.moveToTable').click(function(event){ 
      $("input:checked").each(function(){ 
       $.post('/table/move-to-table', 
       {orderID: $(this).val(), 
        tableID: $('#moveToTableID').val() 
       }, 
       function(data){ 
        location.reload(); 
       }); 
      }); 
      //location.reload(); 
     }); 

回答

6

一种简单的方法是将元素数量存储在全局范围内并将其减去。当最后一个元素完成请求时,它将重新加载。请注意,如果某个请求返回错误,则会失败,您必须处理错误事件并减去window.Remaining。两次或多次点击也可能破坏此方法。

window.Remaining = 0; 
$('button.moveToTable').click(function(event){ 
    window.Remaining = $("input:checked").length; 
    $("input:checked").each(function(){ 
     $.post('/table/move-to-table', 
     {orderID: $(this).val(), 
      tableID: $('#moveToTableID').val() 
     }, 
     function(data){ 
      --window.Remaining; 
      if (window.Remaining == 0) 
       window.location.reload(); 
     }); 
    }); 
    //location.reload(); 
}); 
+1

使用'length'属性的好主意。你可以避免像'window.Remaining = $('input:checked')。each(function(){...}).''这样的操作两次运行选择器。 :o) – user113716 2010-10-13 23:22:53

+0

只是一个旁注:你为什么把这个放在'window'下面?这在本地范围内也会起作用。不需要污染全局名称空间。 – 2010-10-13 23:39:44

5

不知道这是最好的解决办法,但一个想法是将增加为每一个发送的请求的数量,然后递减它作为请求返回。

使用计数作为标志来确定reload()是否应该触发。

事情是这样的:

var count = 0; 

$('button.moveToTable').click(function(event){ 
      $("input:checked").each(function() { 
       count++; // Increment the counter for each request 

       $.post('/table/move-to-table', 
       {orderID: $(this).val(), 
        tableID: $('#moveToTableID').val() 
       }, 
       function(data) { 
        count--; // Decrement as the requests return 

         // Only reload if the count is 0 
        if(count === 0) 
         location.reload(); 
       }); 
      }); 
     }); 

你或许应该有一些代码,以防止click从第二点击发生。你可以使用相同的count变量。

如:

if(count === 0) { 
    $("input:checked").each(func... 

或者一个更好的想法可能是使用this solution from nsw1475和所有复选框只发送一个请求,如果该选项提供给您。

2

一个更好,更高效和无缺陷的方法可能是使用each()函数来生成一个json数组,存储哪些复选框已被选中,然后使用.post将所有数据传递到一起。完成后,调用页面刷新。