javascript - 带有数据变量的 json 请求 - 如何读取函数中的变量?

标签 javascript jquery json function variables

从名为 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
        }
    }

最佳答案

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));

}

关于javascript - 带有数据变量的 json 请求 - 如何读取函数中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15281421/

相关文章:

javascript - 如何从字符串中分离数字和算术运算符?

javascript - 通过 Python Boto3 为 cognito 用户启用 SOFTWARE_TOKEN_MFA

javascript - 如果单击提交按钮,则防止执行 beforeunload 函数

database - node.js 存储数据的一些问题

javascript - 迭代未知复杂度的复杂 JSON 对象

java - 将异常转换为 JSON

javascript - 组合 if 语句

javascript - 如何获取mp3文件的大小和持续时间?

jQuery Slider 不拾取换行符上的元素

jquery - 向右浮动 div 在左侧创建灰色区域