use*_*530 5 javascript ajax jquery
嗨,我有一个很大的问题,一直困扰着我很长一段时间,大部分时间我都能避免它,但现在没有别的办法了.下面是一个函数,在执行时会为每个复选框发送一个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();
});
Run Code Online (Sandbox Code Playgroud)
一种简单的方法是将元素的数量存储在全局范围中并减去它们.当最后一个元素完成请求时,它将重新加载.请注意,如果某些请求返回错误,则会失败,您必须处理错误事件以及减去错误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();
});
Run Code Online (Sandbox Code Playgroud)
不确定这是否是最佳解决方案,但一个想法是增加为每个请求发送的请求的计数,然后在请求返回时减少它.
使用计数作为标志来确定是否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();
});
});
});
Run Code Online (Sandbox Code Playgroud)
你可能应该有一些代码来防止click第二次点击发生.你可以使用相同的count变量.
如:
if( count === 0 ) {
$("input:checked").each(func...
Run Code Online (Sandbox Code Playgroud)
或者更好的想法可能是使用nsw1475中的此解决方案,并且如果您可以使用该选项,则只为所有复选框发送一个请求.