嗨,我有一个巨大的问题,这个问题已经困扰我很长一段时间了,大多数时候我都能够避免它,但现在没有其他方法了。下面是一个函数,它在执行时为每个复选框发送一个post请求。我需要它等到$.each完成刷新页面。我使用location.reload在每个函数的回调函数和每个函数的外部函数中执行了测试。在10个选中的框中,只有7-8个框在$.each的回调中进行了重新加载,如果在$.each之后移动,则会处理3-4个框(仍在.click中)。我需要它以某种方式等待$.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();
});发布于 2010-10-14 07:13:52
一种简单的方法是存储全局作用域中的元素数量,然后减去它们。当最后一个元素完成请求时,它将重新加载。请注意,如果某些请求返回错误,则此操作将失败,您还必须处理error事件并减去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();
});发布于 2010-10-14 07:14:31
不确定这是否是最好的解决方案,但一个想法是增加每个请求发送的请求计数,然后在请求返回时减少它。
使用计数作为标志来确定是否应该触发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,如果该选项对您可用,则只为所有复选框发送一个请求。
发布于 2010-10-14 07:27:15
一种更好、更有效且无bug的方法可能是使用each()函数生成一个json数组,存储已选中的复选框,然后使用.post一起传递所有数据。完成后,调用page refresh。
https://stackoverflow.com/questions/3928790
复制相似问题