简体   繁体   English

如何在循环期间访问jquery getJson调用($ .getJson)中的索引变量?

[英]How to access index variable in a jquery getJson call ($.getJson) during a loop?

I have the following code, which has been simplified for this question. 我有以下代码,已针对该问题进行了简化。 Basically i have a loop, that, on each iteration, calls the jquery getJSON function, calling out to a API end point to grab some weather data. 基本上,我有一个循环,在每次迭代中都调用jquery getJSON函数,并调出到API端点以获取一些天气数据。 The problem is that i need to access the index from the loop, when the getJSON request was fired, and am having some troubles with it. 问题是,当触发getJSON请求时,我需要从循环访问索引,并且遇到了一些麻烦。 I need to know what index the request was for, so i can match it with some data from a database. 我需要知道请求的索引,因此我可以将其与数据库中的某些数据进行匹配。

The code: 编码:

function buildCities()
{    
    for (var i = 0; i < 7; i++) 
    {
        var jqxhr = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=usa,phoenix&units=metric", function(response) 
       {
           alert(i); //this will always be 7 - this is the issue.  i desire it to be 0,1,2,3, etc.... 
       });
    }
}

Here is a JSFiddle that shows the issue, and that you can work on if need be ;) - http://jsfiddle.net/5tr34k/0xshvrzp/ 这是一个显示问题的JSFiddle,您可以根据需要进行操作;)-http: //jsfiddle.net/5tr34k/0xshvrzp/

The request: How can i inject or otherwise access this index (i) inside of the callback function for the request ? 请求:如何在请求的回调函数内注入或访问此索引(i)? Thanks for any help. 谢谢你的帮助。

Add a scoping function (an IIFE) that creates a new scope for your variable: 添加作用域函数(IIFE),该函数为变量创建新作用域:

function buildCities()
{    
    for (var i = 0; i < 7; i++) 
    {
        (function(index){
            var jqxhr = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=usa,phoenix&units=metric", function(response) 
           {
                alert(index); 
           });
        })(i);
    }
}

Also if you have access to ES6 changing i to val instead of var will also work. 另外,如果您可以访问ES6,则将i更改为val而不是var也可以。

Main issue is you are dealing with function scoping so you keep reusing the same variable vs val which is {} scoped, or TrueBlueAussie answer which creates a new scope for you. 主要问题是您正在处理函数作用域,因此您将继续重用{}范围内的相同变量vs val,或TrueBlueAussie答案为您创建新范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM