简体   繁体   English

Jquery绑定循环变量到getJSON函数

[英]Jquery binding loop variable to getJSON function

I have a for loop that GETs a json array and populates it in a table along with another list's variables. 我有一个for循环,它获取一个json数组,并将其与另一个列表的变量一起填充到表中。 My problem is I am not able to access i inside the get method. 我的问题是我无法在get方法中访问i。 But I have mylist and all its contents inside. 但我有mylist及其所有内容。 I tried binding the function to a variable i using bind(this,i) but that says .getJSON() is not a function. 我尝试使用bind(this,i)将函数绑定到变量i,但是说.getJSON()不是函数。 Here's the relevant code. 这是相关的代码。

var mylist = ["a", "b", "c"]
for (i = 0; i < mylist.length; i++) {

    urlstr = "/" + mylist[i]; // Generate url
    $.getJSON(urlstr, function(data) {
        html = "<tr><td>" + mylist[i] + "</td><td>" + data.string[0] + "</td></tr>";
        $("#tableresult").append(html); //this returns undefined for mylist[i]
        console.log(i); //this returns 3 which is the length of list
    });

}

In short I need the variables outside getJSON be accessible within getJSON. 简而言之,我需要在getJSON中访问getJSON之外的变量。 Can someone please help? 有人可以帮忙吗? Thanks and regards. 谢谢并恭祝安康。

This should be no different from binding the loop variable in practically any other loop. 这应该与几乎任何其他循环中的循环变量绑定无异。 Since you are working with an array, the cleanest approach is to use Array#forEach : 由于您正在使用数组,最干净的方法是使用Array#forEach

var mylist = ["a", "b", "c"];
mylist.forEach(function (item) {
    var urlstr = "/" + item;
    $.getJSON(urlstr, function(data){
         var html = "<tr><td>" + item + "</td><td>" + 
                    data.string[0] + "</td></tr>";
         $("#tableresult").append(html);
        console.log(item);
    });
});

please ensure your php return data is json. 请确保您的PHP返回数据是json。

for example: 例如:

$data['something'] = 'data';
echo json_encode($data);

and using function for get index (i): 并使用函数获取索引(i):

 $.getJSON("demo_ajax_json.js", function(result){
        $.each(result, function(i, field){
            $("div").append(field + " ");
        });
    });

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

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