简体   繁体   中英

How can I append values from an Ajax response to an array in JavaScript?

Before my Ajax function is called, I have a global scoped names array like this:

var names =  ["John Smith","Mike Jones","Jenny White","April Brown"];

In the success function of the ajax call I need to erase the array and repopulate it with new names passed back to the page in Json format ( v.name in the example below).

But I'm not sure how to append to the array in the course of my $.each loop:

$.each(data, function() {
  $.each(this, function(k, v) {

      // how to add `v.name` to the `names` array?

  });
});

Assuming you have already cleared names , try this:

$.each(data, function() {
  $.each(this, function(k, v) {
      names.push(v.name);
  });
});

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