多个AJAX相互依赖并在其中循环

时间:2017-11-29 08:17:20

标签: javascript jquery ajax asynchronous callback

我需要进行AJAX调用并返回其数据。当它成功时,它应循环遍历每个数据并为每次迭代运行另一个AJAX函数。

问题是某些行是异步跳过的,所以它会向下一个依赖它的AJAX发送不同的数据。我在代码中添加了一个注释错误的地方。

var total_sections_num;

var question_arr;

var section_arr;

function populateCreateSurvey(){

    $.ajax({

        type: 'get',

        url: "{{ url('importsurvey') }}",

        data: { survey_id: selected_survey },

        success:function(data){

            question_arr = [[],[]];

            section_arr= [];

            $(data).each(function(item, value){

                $('#survey_title').val(value.name);

                var selected_survey_id = value.survey_id;

                $.ajax({

                    type: 'get',

                    url: "{{ url('importsections') }}",

                    data: { survey_id: selected_survey_id },

                    success:function(data){

                        total_sections_num = 0;

                        $(data).each(function(item,value){

                            section_arr[total_sections_num++] = value.title;

                            var section_id = value.section_id;

                            $.ajax({

                                type: 'get',

                                url: "{{ url('importquestions') }}",

                                data: { section_id: section_id },

                                success:function(data){

                                    if (!(data.length ===0)){

                                        var i = 0;

                                        question_arr[total_sections_num] = [];

                                        $(data).each(function(item,value){

    //here is where it doesn't work as how it's supposed to. Once it gets here, total_sections_num's value is already 2 when it's supposed to be 1 first.   

                                        question_arr[total_sections_num][i++] = value.content;

                                        });

                                    }

                                }

                            }); 

                        });

                    }

                });

            });

        }

    });

}

0 个答案:

没有答案