gpt4 book ai didi

javascript - 循环内的 AJAX 请求

转载 作者:行者123 更新时间:2023-12-01 01:14:38 24 4
gpt4 key购买 nike

我试图在循环内调用多个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() 执行此 Promise 数组。

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)

关于javascript - 循环内的 AJAX 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54880439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com