[英]From an ajax json request, how can dynamically add the objects to an array so that I can loop through them?
This is what I have so far, essentially I'd like to use the data to instantiate a new info-window from google maps api dynamically from the data response. 到目前为止,这就是我要的东西,本质上,我想使用数据从数据响应中动态地实例化来自Google Maps API的新信息窗口。 I know so far that I'm pushing objects to an array(which are two different data types), but if that's the only wrong here.
到目前为止,我知道我正在将对象推入数组(这是两种不同的数据类型),但是如果这是唯一的错误。 Then how can I dynamically add the response into an object so I can retrieve data with a loop?
然后,如何动态地将响应添加到对象中,以便可以通过循环检索数据?
var i, venues, allVenues=[];
$.ajax({
url: 'url',
dataType: 'json',
data: 'data'
async: true,
success: function(data) {
venues = data['response']['groups'][0]['items'];
JSON.parse(venues);
for(i in venues){
allVenues.push(venues[i]);
}
};
/*Do something realistic with data other than logging it to console*/
console.log(allVenues);
You do it right, but not in the right place. 您做对了,但是没有在正确的地方进行。 jQuery.ajax will not wait for the response, but will invoke a 'success' callback when the request is answered.
jQuery.ajax不会等待响应,但会在请求得到响应时调用“成功”回调。
Try this: 尝试这个:
var i, venues, allVenues=[];
$.ajax({
url: 'url',
dataType: 'json',
data: 'data'
async: true,
success: function(data) {
venues = data['response']['groups'][0]['items'];
// The following line of code does nothing, because you
// did not store it's return value. Fortunately it wasn't
// even needed
//
// JSON.parse(venues);
for(i in venues) {
allVenues.push(venues[i]);
}
// or
// allVenues.push.apply(allVenues, venues);
// or in ES6
// allVenues.push(...venues);
// or the following will create a new array instance and save it in the allVenues variable
// allVenues = allVenues.concat(venues);
/*Do something realistic with data other than logging it to console*/
console.log("Here are your updated venues:");
console.log(allVenues);
}
});
console.log("These are your old venues:");
console.log(allVenues);
EDIT: You can check that the identity of the allVenues array didn't change by printing it to the console every second: 编辑:您可以通过每秒将其打印到控制台来检查allVenues数组的标识是否未更改:
setInterval(function(stored) {
console.log(stored);
console.log(stored === allVenues);
}, 1000, allVenues);
EDIT: To update an array to contain only the items of another array, you can use: 编辑:要更新一个数组以仅包含另一个数组的项目,可以使用:
allVenues.length = 0;
allVenues.push.apply(allVenues, venues);
or 要么
allVenues.length = venues.length;
for (var i in venues) {
allVenues[i] = venues[i];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.