簡體   English   中英

Jquery綁定循環變量到getJSON函數

[英]Jquery binding loop variable to getJSON function

我有一個for循環,它獲取一個json數組,並將其與另一個列表的變量一起填充到表中。 我的問題是我無法在get方法中訪問i。 但我有mylist及其所有內容。 我嘗試使用bind(this,i)將函數綁定到變量i,但是說.getJSON()不是函數。 這是相關的代碼。

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

}

簡而言之,我需要在getJSON中訪問getJSON之外的變量。 有人可以幫忙嗎? 謝謝並恭祝安康。

這應該與幾乎任何其他循環中的循環變量綁定無異。 由於您正在使用數組,最干凈的方法是使用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);
    });
});

請確保您的PHP返回數據是json。

例如:

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

並使用函數獲取索引(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