简体   繁体   中英

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. My problem is I am not able to access i inside the get method. But I have mylist and all its contents inside. I tried binding the function to a variable i using bind(this,i) but that says .getJSON() is not a function. 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. 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 :

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.

for example:

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

and using function for get index (i):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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