从一个名为bunchOfData的数组中加载一堆json文件。 .url是每个json文件的URL。
如何在 processData 函数中读取变量“myI”?
for(var i = 0; i < bunchOfData.length; i++){
$.getJSON(bunchOfData[i].url, {"myI":i}, function(ds){}).success(processData);
function processData(ds){
console.log(ds.myI); //undefined
}
}
答案 0 :(得分:1)
function successHandler(i){
console.log('i is instantiated/stored in the closure scope:',i);
return function(data, textStatus, jqXHR){
// here, the server response and a reference to 'i'
console.log('i from the closure scope:',i, 'other values',data,textStatus,jqXHR);
}
}
var i = 0; i < bunchOfData.length; i++){
$.getJSON(bunchOfData[i].url, {"myI":i}, function(ds){}).success(successHandler(i));
}
答案 1 :(得分:0)
您无法访问范围之外的变量,响应只会有效
function(ds){
// Here
}
试试这个:
for(var i = 0; i < bunchOfData.length; i++){
$.getJSON(bunchOfData[i].url, {"myI":i}, function(ds){
console.log(ds);
});
}
一旦请求完成并且success
的成功内容将会运行,请注意您尝试获取的内容可能不是单个请求(您可以统一文件并将其保存在一个文件中) ),所以你得到数据,然后迭代。