繁体   English   中英

从ajax json请求中,如何将对象动态添加到数组中,以便我可以遍历它们?

[英]From an ajax json request, how can dynamically add the objects to an array so that I can loop through them?

到目前为止,这就是我要的东西,本质上,我想使用数据从数据响应中动态地实例化来自Google Maps API的新信息窗口。 到目前为止,我知道我正在将对象推入数组(这是两种不同的数据类型),但是如果这是唯一的错误。 然后,如何动态地将响应添加到对象中,以便可以通过循环检索数据?

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

您做对了,但是没有在正确的地方进行。 jQuery.ajax不会等待响应,但会在请求得到响应时调用“成功”回调。

尝试这个:

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

编辑:您可以通过每秒将其打印到控制台来检查allVenues数组的标识是否未更改:

setInterval(function(stored) {
  console.log(stored);
  console.log(stored === allVenues);
}, 1000, allVenues);

编辑:要更新一个数组以仅包含另一个数组的项目,可以使用:

allVenues.length = 0;
allVenues.push.apply(allVenues, venues);

要么

allVenues.length = venues.length;
for (var i in venues) {
  allVenues[i] = venues[i];
}

暂无
暂无

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

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