在PHP中,我知道每个函数都可以返回true / false。JavaScript也是一样,如何$.each
通过true / false操作jQuery迭代?我的意思是我该如何告诉迭代在得到响应之前保持不变?
现在我正在使用setTimeout()
jQuery中的函数,但是我想替换为true / false响应并转到下一个迭代,有没有办法?
我的脚本是:
$(document).on( "click", '#sync',function(e) {
e.preventDefault();
$('#sync').prop('disabled', true);
$.ajax({
type: "POST",
url:"./post/dataUrl",
data: {},
dataType: 'json',
success: function(data){
if(data.status == 'success'){
console.log('Success, lets start the sync !');
$.each(data.data, function(i,item){
setTimeout(function() {
syncData(item.product_id);
var percentage = Math.ceil((i/data.total)*1000)/10;
$('#test').html('<div class="note note-success"><p>The sync is working... '+percentage+'% '+i+'/'+data.total+' <code>'+item.product_id+'</code></p></div>')
if(i == data.total - 1){
$('#sync').prop('disabled', false);
$('#test').empty();
}
}, i * 500); //So, in practic it runs after each 500ms, how can i replace this by standing on the response of syncData(product_id) ?
});
return false;
}
}
});
});
function syncData(product_id){
$.ajax({
type: "POST",
url:"./post/dataSave",
data: {product_id: product_id},
dataType: 'json',
success: function(data){
if(data.status == 'success'){
return true;
}
}
});
}
您不能真正阻止每个循环迭代立即彼此立即运行。听起来更像是您希望回调触发下一项。我没有亲自测试过此代码,但是它应该给您一些提示。对于每个完成的syncData,它将同步下一个项目。
$(document).on( "click", '#sync',function(e) {
e.preventDefault();
$('#sync').prop('disabled', true);
$.ajax({
type: "POST",
url:"./post/dataUrl",
data: {},
dataType: 'json',
success: function(data){
if(data.status == 'success'){
console.log('Success, lets start the sync !');
function syncItem(i) {
var percentage = Math.ceil((i/data.total)*1000)/10;
$('#test').html('<div class="note note-success"><p>The sync is working... '+percentage+'% '+i+'/'+data.total+' <code>'+item.product_id+'</code></p></div>')
if (i == data.total) {
$('#sync').prop('disabled', false);
$('#test').empty();
} else {
var item = data.data[i];
syncData(item.product_id, function () {
// Here we make the next item sync
syncItem(i + 1);
}
}
}
if (data.total > 0) {
syncItem(0);
} else {
// handle empty data case
}
}
}
});
});
function syncData(product_id, callback){
$.ajax({
type: "POST",
url:"./post/dataSave",
data: {product_id: product_id},
dataType: 'json',
success: function(data){
if(data.status == 'success'){
callback();
}
}
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句