繁体   English   中英

循环内的AJAX请求

[英]AJAX requests inside a loop

我试图在循环内调用多个Ajax请求以加载多个下拉列表。 我尝试了顺序方式,我可以看到仅循环中的最后一项被值填充

 var targetcontrols = [];
        var targetcontrols_array = targetControl.split(',');
        var targetsourcecontrols = [];
        var targetsource_array = targetSource.split(',');
        for(i=0; i < targetcontrols_array.length; i++)
        {
            var control_name=targetcontrols_array[i];
            var source=targetsource_array[i];
            $.ajax({
                url: action_url,
                type: 'POST',
                traditional: true,
                async: false,
                data: JSON.stringify( { allselected: allselected_flag, selectedIds: selectedvalues,targetControl:control_name,  targetSource: source, dependency: dependencyOptions } ),
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function (response) {
                    //To clear existing items
                    var target= $("#"+response.targetControl);
                    target.multiselect('dataprovider', []);
                    var dropdown2OptionList = [];
                    for (i = 0; i < response.values.length; i++) {
                        dropdown2OptionList.push({
                            'label': response.values[i].text,
                            'value': response.values[i].value
                        })
                    }
                    console.log("--control"+control_name);
                    //re initialize the search plugin
                    target.multiselect('dataprovider', dropdown2OptionList);
                    target.multiselect('rebuild');
                }
            });

我如何确保循环中的第一项也充满响应值

您可以尝试map产生Promise数组。 之后,使用Promise.all()执行此promises数组。

 var targetcontrols = []; var targetcontrols_array = targetControl.split(','); var targetsourcecontrols = []; var targetsource_array = targetSource.split(','); const arrOfPromises = targetcontrols_array.map(function(item, index) { const control_name = item; const source = targetsource_array[index]; return new Promise((resolve) => { $.ajax({ url: action_url, type: 'POST', traditional: true, async: false, data: JSON.stringify( { allselected: allselected_flag, selectedIds: selectedvalues,targetControl:control_name, targetSource: source, dependency: dependencyOptions } ), contentType: "application/json; charset=utf-8", dataType: 'json', success: function (response) { //To clear existing items var target= $("#"+response.targetControl); target.multiselect('dataprovider', []); var dropdown2OptionList = []; for (i = 0; i < response.values.length; i++) { dropdown2OptionList.push({ 'label': response.values[i].text, 'value': response.values[i].value }) } console.log("--control"+control_name); //re initialize the search plugin target.multiselect('dataprovider', dropdown2OptionList); target.multiselect('rebuild'); resolve(`done for url ${control_name}`) // Show log for checking process } }) }) Promise.all(arrOfPromises) 

这两个声明:

var control_name = targetcontrols_array[i];
var source = targetsource_array[i];  

可能导致问题。 因为var具有function scope并且for loopblock scope ,所以当您使用循环时,将这些control_namesource变量从下一个替换,然后再用于ajax请求中。 这就是为什么您总是得到最后的。 您应该将var更改为constlet支持block scope

const control_name = targetcontrols_array[i];
const source = targetsource_array[i];

首先,如果您使用jquery,请充分利用其潜力,而不是for循环,请使用$.each

var targetcontrols = [];
        var targetcontrols_array = targetControl.split(',');
        var targetsourcecontrols = [];
        var targetsource_array = targetSource.split(',');
        $.each(targetcontrols_array, function(i, item)
        {
            var control_name=targetcontrols_array[i];
            var source=targetsource_array[i];
            $.ajax({
                url: action_url,
                type: 'POST',
                traditional: true,
                async: false,
                data: JSON.stringify( { allselected: allselected_flag, selectedIds: selectedvalues,targetControl:control_name,  targetSource: source, dependency: dependencyOptions } ),
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function (response) {
                    //To clear existing items
                    var target= $("#"+response.targetControl);
                    target.multiselect('dataprovider', []);
                    var dropdown2OptionList = [];
                    $.each(response.values, function(v, vItems) {
                        dropdown2OptionList.push({
                            'label': response.values[v].text,
                            'value': response.values[v].value
                        })
                    });
                    console.log("--control"+control_name);
                    //re initialize the search plugin
                    target.multiselect('dataprovider', dropdown2OptionList);
                    target.multiselect('rebuild');
                }
            });
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM