jQuery Ajax等待每个函数

Im *_*eat 2 javascript ajax jquery 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();
        }          

    });  

  });
});
Run Code Online (Sandbox Code Playgroud)

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

Ben*_*aum 5

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

$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.
});
Run Code Online (Sandbox Code Playgroud)

注意我可以通过.reduce缩短从6到4的行数来"聪明起来" ,但老实说,我宁愿保持循环结构OP很舒服.这是因为承诺链接 - 基本上当你从then它返回一个动作时它将等待它,然后执行下一个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);
     });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

请注意,这样做$xy('#result'+div)可能是一个坏主意,因为您要查看视图层以查找放在那里的内容 - 请考虑将相关div保留为数组并保留引用:)