简体   繁体   中英

How to copy array of objects from ajax call to observable array?

I have an function where i do ajax call and i get the data in callback. Something like this

function loadData(callback) {
   //do ajax
   if(callback) {
      callback(data.data);
   }
}

And if i call the function like

loadData(function(data) {
   return data;
})

it returns the data i need. How can i copy all the objects and its key/values to an self.dataset = ko.observableArray([]); So i can use the data anywhere i want?

How I do it is by using the Knockout Mapping Plugin and the fromJSON command (you might need to use fromJS depending on your data format) this maps the data as it comes from the source.

function loadData() {
    $.ajax({
        url: 'http://...',
        dataType: 'json',
        success: function (data) {
            ko.mapping.fromJSON(data, {}, self.dataArray);
        }
    });
}

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