![](/img/trans.png)
[英]How to access index variable in a jquery getJson call ($.getJson) during a loop?
[英]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.