嵌套的ajax父级在子级完成之前完成

时间:2015-06-15 13:33:50

标签: jquery ajax json nested

$.ajax(
        {
            type: 'POST',
            url: '@Url.Action("EkranListeleSektor")',
            dataType: 'json',
            async: false, //added async later, no changes
            data: { sektorID: $("#ekranSektorID").val() },

            success: function (items) {
                $.each(items, function (i, ekranlar) {

                    $.ajax({
                        type: 'POST',
                        url: '@Url.Action("IlAdGetir")',
                        dataType: 'json',
                        data: { id: ekranlar.il },
                        success: function (ilAd) {
                            strIlAd = ilAd;
                        },
                        error: function (ex) {
                            alert('İl isim çekilemedi.' + ex);
                        }
                    });


                    $.ajax({
                        type: 'POST',
                        url: '@Url.Action("IlceAdGetir")',
                        dataType: 'json',
                        data: { id: ekranlar.ilce },

                            success: function (ilceAd) {
                                alert(ilceAd);
                            strIlceAd = ilceAd;
                        },
                        error: function (ex) {
                            alert('İlce isim çekilemedi.' + ex);
                        }
                    });

                    divContent += '<label class="styledLabel">' +
                        ' <img src=' + (ekranlar.resimURL).replace('~', '') + ' style="height:150px;width:150px;"/>' +
                        '<input type="checkbox" id="' + ekranlar.ekranID + '" name="' + ekranlar.ekranAd + '" value="' + fiyat +
                                    '" class="styledCheck">' + '<br /><span>Ekran İsim: </span><span class="spanEkranAd">' + ekranlar.ekranAd +
                                    '</span><br /><span>' + 'Günlük Fiyat' + ': </span>' + fiyat + '<br /><span>Ekran Boyutu: </span><span class="spanEkranBoyut">'
                                    + ekranlar.ekranBoyutID + '"</span> <br/>' +
                                    '<span class="spanIl">' + strIlAd + '</span><br/> <span class="spanIlce">' + strIlAd + '</span> </label>';

                    $("#imgDiv").append(divContent);
                });
            }, error: function (ex) {
                alert('Ekranlar Çekilemedi.' + ex);
            }
        });
    }

我的动作部分正常工作我可以看到即将发布的数据与警报和调试器,但“EkranListeleSektor”在嵌套的“IlAdGetir”或“IlceAdGetir”开始之前完成,因此当我尝试将输出打印到div时,strIlAd和strIlceAd打印未定义。

2 个答案:

答案 0 :(得分:1)

您应该强烈考虑在此处使用延迟对象来解决您的问题。让我举一个例子来说明你应该如何使用jQuery方便的when()方法:

// This would be code in success handler for your outermost $.ajax() call.
// start "nested" ajax calls wrapped in when()
$.when(
    $.ajax({
        type: 'POST',
        url: '@Url.Action("IlAdGetir")',
        dataType: 'json',
        data: { id: ekranlar.il }
    }),
    $.ajax({
        type: 'POST',
        url: '@Url.Action("IlceAdGetir")',
        dataType: 'json',
        data: { id: ekranlar.ilce },
    })
).done(function(firstCall, secondCall) {
    // This is triggered when both calls are successful
    // set variables
    strIlAd = firstCall[0];
    strIlceAd = secondCall[0];
    divContent += '<label class="styledLabel">' +
    ' <img src=' + (ekranlar.resimURL).replace('~', '') +
    ' style="height:150px;width:150px;"/>' +
    '<input type="checkbox" id="' + ekranlar.ekranID + '" name="' + ekranlar.ekranAd + '" value="' + fiyat +
    '" class="styledCheck">' + '<br /><span>Ekran İsim: </span><span class="spanEkranAd">' + ekranlar.ekranAd +
    '</span><br /><span>' + 'Günlük Fiyat' + ': </span>' + fiyat + '<br /><span>Ekran Boyutu: </span><span class="spanEkranBoyut">'
    + ekranlar.ekranBoyutID + '"</span> <br/>' +
    '<span class="spanIl">' + strIlAd + '</span><br/> <span class="spanIlce">' + strIlAd + '</span> </label>';
    $("#imgDiv").append(divContent);
}).fail(function(){
    // your failure handler, triggered when either ajax call fails
});

您可以看到这真正整合了您的代码,在一个地方获得了所有成功处理和失败处理。

在性能方面和用户体验方面,您可能会发现这比使用同步ajax调用更可取,当您从外部ajax调用遍历每个记录并阻止用户浏览器执行任何其他操作时每个都有两个嵌套调用。

答案 1 :(得分:0)

I already post my answer in comments anyway I can think in 2 ways to try solving your issue:

  1. Add async: false, to your nested calls
  2. Try moving your div print out to the last (the second one) nested "success" call, but first verify all the calls are being executed using debug tools (debug tools -> network).