javascript - jQuery Ajax 等待每个函数

标签 javascript jquery ajax promise jquery-deferred

$xy('#simpan').click(function() {

  $xy('input[id="cekbok[]"]:checked').each(function() {

    var data = (this.value);
    var div = (this.value);
    var str = window.location.href;
    var res = str.replace("wp-admin/options-general.php?page=katalogu-options", "/wp-content/plugins/katalog/includes/img/loading.gif");
    var loading = ('<img src="'+res+'">') ;


    $xy.ajax({
        type : 'POST',
        url : '../wp-content/plugins/katalogunique/proses2.php',           
        data: {
            id  : (this.value)
        },

        success:function (data) {
            $xy('#result'+div).empty();
            $xy('#result'+div).append(data);
            $xy('#tz'+div).remove();
        }          

    });  

  });
});

我的函数在一个循环中将复选框值发送到 proses2.php 但是当我运行这个脚本时它会立即运行所有的 ajax POST 调用。我想一个接一个地运行 ajax 请求或等到完成,我该如何解决这个问题?

最佳答案

这是一种没有递归并使用简单循环的方法:

$xy('#simpan').click(function() {

    var url = '../wp-content/plugins/katalogunique/proses2.php';
    var d = $.Deferred().resolve(); // empty promise
    $xy('input[id="cekbok[]"]:checked').each(function() {
        var div = this.value;
        d = d.then(function(data){
            $xy('#result'+div).empty().append(data);
            $xy('#tz'+div).remove();
            return $xy.post(url, {id: div}); // this will make the next request wait
        });
    });
    // can d.then here for knowing when all of the requests are done.
});

请注意,我可以使用 .reduce 将行数从 6 缩短到 4,从而“巧妙地解决这个问题”,但老实说,我宁愿让循环构造让 OP 感到舒服。这是有效的,因为 promise 链接 - 基本上当你从 then 返回一个 Action 时,它会等待它,然后再执行你链接到的下一个 then

让我们举个例子:

function log(msg){ // simple function to log stuff
    document.body.innerHTML += msg + "<br />";
}

var delay = function(ms){ // this is an async request, simulating your AJAX
   var d = $.Deferred();
   setTimeout(d.resolve, ms); // resolving a deferred makes its then handlers execute
   return d;
};

// $.Deferred.resolve() starts a new chain so handlers execute
var p = $.Deferred().resolve().then(function(){ 
    log("1");
    return delay(1000); // like in your code, we're waiting for it when we chain
}).then(function(){ // in the above code, this is the d = d.then part,
    log("2"); // this only runs when the above delay completes
    return delay(1000);
});

// and more like in the above example, we can chain it with a loop:
[3,4,5,6,7,8,9,10].forEach(function(i){
     p = p.then(function(){
         log(i);
         return delay(1000);
     });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

请注意,执行 $xy('#result'+div) 可能是个坏主意,因为您正在查询 View 层以查找放置在那里的内容 - 考虑将相关的 div 保留为数组并保留引用:)

关于javascript - jQuery Ajax 等待每个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30096628/

相关文章:

Javascript extending an object 问题

javascript - 如何让这个表单在提交时做两件事(AJAX 和 PHP 邮件)?

javascript - 我应该将 php json 编码转换为 Ajax 数组,第一次对我来说很难理解

javascript - 使用 AJAX 和 PHP 删除用户记录时面临的问题

php - 更新 "quantity remaining"而不刷新站点

javascript - 添加第二个类不起作用

javascript - 从html中的输入获取文件路径

javascript 创建的控件值未发布到服务器

javascript - 如何使用 Javascript 将文本添加到单选按钮?

javascript - 正文溢出:visible on pop up close