【问题标题】:Ajax success function to fire another ajax function whilst iterating through loopAjax 成功函数在遍历循环时触发另一个 ajax 函数
【发布时间】:2017-05-30 09:03:33
【问题描述】:

我有以下 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 文件中的一部分数据需要注入到模板中,因为它在循环中进行迭代。

看起来循环的工作原理是,在这个例子中,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(){

                    }
                });
            }
        },

但我尝试过的一切似乎都返回了相同的结果。

【问题讨论】:

  • 你可以遍历你的 JSON 文件,并使用 Promise.all。
  • 你能举个例子吗。我认为 promise 会等到事件完成,我需要一种方法来在遍历循环时触发第二个函数。
  • 由于您使用jQuery,请看这里:stackoverflow.com/questions/16026942/…
  • @VedranMaricevic 除非我弄错了,否则链接与我想要的相反。

标签: javascript jquery ajax for-loop


【解决方案1】:

代码已经被重写了一些,但这是我正在做的。

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 中的项目与模板中的项目匹配。

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多