我有一系列对外部 API 的嵌套 Ajax 请求,这非常难看,但这是我能够弄清楚如何按指定顺序进行调用的唯一方法,每个调用都利用从前一个调用带回的一些值。 (我尝试 this 但无法让它工作,所以我恢复了建议 here 。)
无论如何,这在某种程度上效果很好。我的所有调用都是连续进行的,最终得到一个名为 people
的数组,它只是一个名称列表:["name1","name2","name3"]
.
我的问题是我似乎无法通过我的 javascript 代码对这个数组执行任何操作。我无法将它们附加到 div,也无法提醒它们,甚至无法在代码执行期间对它们进行 console.log。然而,一旦我的代码完成,我就可以在浏览器控制台中输入 people
,然后他们就按预期出现了。
我猜测这与变量的范围有关 - 我尝试将其设为全局并移动其声明的位置,但这是我从可运行对象访问 people
的唯一方法代码来自最终的 AJAX 循环,然后我得到很多重复值,因为它正在循环并增量添加到数组中。
这里的目标是让人们参与最终的 API 调用并在 HTML 中列出他们。
这是我的代码。非常感谢任何建议。
触发事件的 HTML:
<input type='file' accept='image/*' onchange='openFile(event)'>
<!--process is triggered by file upload-->
javascript:
var openFile = function(event) {
//... Some UI stuff happens here.
//... When finished, just call getGraph(); below
performances = new Array(); // global scope
people = new Array(); // global scope
getGraph(); // call function below
console.log(people); // retrieve array; doesn't work
};
function getGraph(){
$.ajax({
url:'http://...' + document.getElementById('prDate').value,
dataType:'json',
success: function(response){
$.each(response, function(i, item) {
var programID = item.id;
$.ajax({
url:'http://...'+ programID',
dataType:'json',
success: function(response){
$.each(response, function(i, item) {
performances.push( item.id );
});
$.each(performances, function(index, value){
$.ajax({
url:'http://...' + this.valueOf() +'/persons/',
dataType:'json',
success: function(response){
$.each(response, function(i, item) {
people.push( item.firstname + ' ' + item.lastname ); // the magic moment
});
}
});
});
}
});
});
}
});
}
最佳答案
从您的代码中可以看出,只有在调用 openfile
函数后才会创建 people
变量。如果您希望即使未调用 openfile 方法也能创建它,请在所有函数之外声明它,然后它将可以访问,或者在您打算使用它的地方声明它,如上面所示ajax 调用,然后使用它。
关于Javascript 全局变量只能在应用程序运行后访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30271992/