【发布时间】: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