在php中我知道每个函数都可以返回true / false。 JavaScript也是这样做的,jQuery $.each
迭代如何通过这个true / false来操作?我的意思是我怎么能告诉迭代留下它才能得到响应?
现在我在jQuery中使用函数setTimeout()
,但我想用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;
}
}
});
}
答案 0 :(得分:2)
您无法确保每个循环迭代不会在彼此之后立即运行。听起来更像是你想要一个回调来触发下一个项目。我自己还没有测试过这段代码,但它应该会给你一些如何做到这一点的提示。对于每个完成的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();
}
}
});
}
答案 1 :(得分:0)
$({}).queue("ajax",
$.map(data.data, function(item, i) {
return function(next) {
setTimeout(function() {
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();
}
// So, in practic it runs after each 500ms,
// how can i replace this by standing on the response of
// syncData(product_id) ?
syncData(item.product_id).then(next)
}, i * 500);
}
})
).dequeue("ajax");