Ajax成功函数在迭代循环时触发另一个ajax函数

时间:2017-05-30 09:03:34

标签: javascript jquery ajax for-loop

我有以下js / jquery代码:

var trigger             = $('#loadTableData');
var wrapperClass        = 'tableAccordionWrapper';
var url                 = 'data/tableData.json';
var template            = 'includes/tableInput.html';
var parentWrapper       = $('#selectedTables .sub-content .input-controls');
var href;
var intID;
var items;
var i;

// retrieve node data send from exteral source
addExternalTableInput = function(){
    $('.tableAccordionWrapper').remove();
    $.ajax({
        type:           'GET',
        url:            url,
        dataType:       'json',
        success:function(data){
            items = data.items
            for(i in items){ // this loops 3 times
                addExternalTemplate();
            }
        },
        error:function(status){
            console.log(status, "Something went wrong");
        },
        complete:function(){

        }
    });
}

// append table input to document
addExternalTemplate = function(){
    var wrapper;
    $.ajax({
        type:           'GET',
        url:            template,
        dataType:       'html',
        success:function(data){
            intID = i;
            wrapper = $('<li/>');
            wrapper.addClass(wrapperClass);
            wrapper.attr('data-id','table-' +intID);
            href = $('<a href="#"/>');
            wrapper.append(href);
            wrapper.append(data).insertBefore(parentWrapper);
            var anchor = wrapper.find('> a');
            anchor.html(items[intID].tableName); // this returns 'DB_SOURCE_3' for all 3 templates added to the DOM
        },
        error:function(status){
            console.log(status, "Something went wrong");
        },
        complete:function(){

        }
    });
}

这个概念是我使用一个小的json文件来运行另一个ajax请求。 json文件中数据的长度决定了应该触发连续函数的次数。

json包含非常基本的数据,但是当我遍历它时,我希望第二个ajax函数将html模板附加到文档中(此时我希望能够运行其他函数)。当json文件迭代循环时,需要将json文件中的一部分数据注入到模板中。

循环似乎是在这个示例中,html模板被附加到dom 3次,但是它将json中的最后一个表名传递给添加到dom的每个模板。第二个函数似乎在循环结束后运行。

示例JSON:

{  
    "items":[  
        {  
            "tableName": "DB_SOURCE_1",
            "tableID" : "14739",
            "tableDescription" : "Main customer table" 
        },
        {
            "tableName": "DB_SOURCE_2",
            "tableID" : "184889",
            "tableDescription" : "Partitions table" 
        },
        {
            "tableName": "DB_SOURCE_3",
            "tableID" : "9441093",
            "tableDescription" : "Loans Table" 
        }
    ]
}

我试过在ajax完成函数中传递函数。

我也尝试在第一个ajax成功函数中触发第二个ajax函数,如下所示:

addExternalTableInput = function(){
    $('.tableAccordionWrapper').remove();
    $.ajax({
        type:           'GET',
        url:            url,
        dataType:       'json',
        success:function(data){
            items = data.items
            for(i in items){
                $.ajax({
                    type:           'GET',
                    url:            template,
                    dataType:       'html',
                    success:function(data){
                        intID = i;
                        wrapper = $('<li/>');
                        wrapper.addClass(wrapperClass);
                        wrapper.attr('data-id','table-' +intID);
                        href = $('<a href="#"/>');
                        wrapper.append(href);
                        wrapper.append(data).insertBefore(parentWrapper);
                        var anchor = wrapper.find('> a');
                        anchor.html(items[intID].tableName);
                    },
                    error:function(status){
                        console.log(status, "Something went wrong");
                    },
                    complete:function(){

                    }
                });
            }
        },

但我尝试过的所有内容似乎都会返回相同的结果。

1 个答案:

答案 0 :(得分:0)

代码已被重写,但这就是我正在做的事情。

var templateData;

addExternalTableInput = function(){
    $('.tableAccordionWrapper').remove();
    $.ajax({
        type:           'GET',
        url:            url,
        dataType:       'json',
        success:function(data){
            var items = data.items;
            for(var i in items){
                addExternalTemplate(items[i], i); // pass parameters to this function
            }
        },
        error:function(status){
            // etc. 
        }
    });
}

addExternalTemplate = function(item, intID){ // add parameters to our function so we can access the same data
    var wrapper;
    // load template data once
    if(!templateData){ // only run this function if !templateData (should only run once).
        $.ajax({
            type:           'GET',
            url:            template,
            dataType:       'html',
            async:          false, // wait until we have a response before progressing
            success:function(data){
                templateData = data;
            },
            error:function(status){
                console.log(status, "Something went wrong");
            }
        });
    }
    // append templateData to the dom
    if(templateData){
        var href = $('<a href="#"/>');
        var tableNameInput = wrapper.find('[name="tables"]');
        tableNameInput.val(item.tableName);
        // etc
    }
    // update for, id and name attributes etc.
    updateInputAttributes = function(){
        // do other stuff to each instance of the template
    }();
}

我已经移出了很多全局变量,而是使用了函数参数。

我只调用一次html模板,但是对于循环的每次迭代,我都可以运行函数来更新模板实例中的某些属性,以及将json中的项目与模板中的项目进行匹配。