调用后不是异步Ajax忽略函数

时间:2016-05-17 15:31:58

标签: javascript jquery ajax

我有以下功能:

    $("#transfer").click(function(){
        var token_rec = $("#token_rec").val();
        var user_rec = $("#user_rec").val();
        var subdomain_rec = $("#subdominio_rec").val();
        var req_rec = $("#req_rec").val();
        var acao_rec = $("#acao_rec").val();
        var section_rec = $("#section_rec").val();
        if(!token_rec || !user_rec || !subdomain_rec || !req_rec || !acao_rec || !section_rec){
            alert("Preencha todos os campos de recebimento.");
        } else {
            $("#transfer").hide();
            $("#loading").show();
            $("#accordion_rec").empty();
            var abody = "";
            var c = $(this).attr("count");
            for(var i=0; i<c; i++){
                if($("#check_ret"+i).is(":checked")){
                    var json_dec = decodeURI($("#check_ret"+i).val());
                    var json_es1 = json_dec.replace(/="/g, '=\\"');
                    var json_es2 = json_es1.replace(/">/g, '\\">');
                    var json_es3 = json_es2.replace(/\r\n|\r|\n/g, '');
                    $.ajax({
                        async: false,
                        type: "POST",
                        url: "php/curlWrap_rec.php",
                        data: {token: token_rec, user: user_rec, subdomain: subdomain_rec, req: req_rec, acao: acao_rec, json: json_es3},
                        success: function(data){
                            var data_parsed = JSON.parse(data);
                            abody+= '<div style="border:solid 1px #ccc">';
                            abody+= '<p style="cursor:pointer" onclick="accordion(\'#rec_slide'+i+'\')"><strong>'+data_parsed.article.title+'</strong></p>';
                            abody+= '<div id="rec_slide'+i+'" style="display:none">'+data_parsed.article.body+'</div>';
                            abody+= '</div>';
                        }
                    });
                }
            }
            $("#loading").hide();
            $("#transfer").show();
            $("#accordion_rec").append(abody);
        }
    });

它工作正常,但它似乎忽略了我隐藏$(&#34; #transfer&#34;)并显示$(&#34; #loading&#)的代码部分34;)在电话会议之前。

为什么会发生这种情况,我该如何纠正?

2 个答案:

答案 0 :(得分:1)

我建议您不要使用async: false。它锁定了浏览器,我认为这是导致您的问题的原因。您的代码未被“忽略”,而是阻止,直到AJAX调用完成。

你应该让AJAX调用保持异步并相应地管理你的回调。

在这种情况下,您需要为每个 AJAX调用创建一个闭包,因为它们当前共享相同的i变量。

for(var i=0; i<c; i++){
    if($("#check_ret"+i).is(":checked")){
        $.ajax({
            type: "POST",
            url: "php/curlWrap_rec.php",
            dataType: 'json', // <- this will call JSON.parse for you
            data: {token: token_rec, user: user_rec, subdomain: subdomain_rec, req: req_rec, acao: acao_rec, json: json_es3},
            success: (function(i){
                // What's happening here is that a *new* function is generated
                // and returned each iteration of the `for` loop.
                // This lets each callback have its own `i` value.
                return function(data){
                    // Since this is now asynchronous, we can't
                    // append to the "global" `abody`, each callback
                    // needs its own.
                    var abody = '<div style="border:solid 1px #ccc">' +
                        '<p style="cursor:pointer" onclick="accordion(\'#rec_slide'+i+'\')"><strong>'+data.article.title+'</strong></p>'+
                        '<div id="rec_slide'+i+'" style="display:none">'+data.article.body+'</div>'+
                        '</div>';
                    $("#accordion_rec").append(abody);
                };
            }(i))
        });
    }
}

你可以做的另一件事是使用deferreds / promises等到所有 AJAX调用完成后再附加到元素。

// We'll store the promises returned by $.ajax here,
// so we can add the callback(s) later
var ajax_calls = [];

$("#transfer").hide();
$("#loading").show();
$("#accordion_rec").empty();

for(var i=0; i<c; i++){
    if($("#check_ret"+i).is(":checked")){
        // This returns a promise which we are saving for later
        ajax_calls.push($.ajax({
            async: false,
            type: "POST",
            url: "php/curlWrap_rec.php",
            data: {token: token_rec, user: user_rec, subdomain: subdomain_rec, req: req_rec, acao: acao_rec, json: json_es3}
        }));
    }
}

// Wait for *all* the promises to complete
$.when.apply($, ajax_calls).done(function(){
    var abody = "";

    // This function is passed one parameter for each AJAX call,
    // in the order they were added to the `ajax_calls` array.
    // So we can just loop over `arguments` and get the correct data
    // and `i` value.
    for(var i=0; i<arguments.length; i++){
        abody+= '<div style="border:solid 1px #ccc">';
        abody+= '<p style="cursor:pointer" onclick="accordion(\'#rec_slide'+i+'\')"><strong>'+arguments[i][0].article.title+'</strong></p>';
        abody+= '<div id="rec_slide'+i+'" style="display:none">'+arguments[i][0].article.body+'</div>';
        abody+= '</div>';
    }

    $("#loading").hide();
    $("#transfer").show();
    $("#accordion_rec").append(abody);
});

答案 1 :(得分:-1)

检查页面只包含一个传输元素和加载元素。如果有多个元素具有相同的ID。