简体   繁体   中英

knockout push data from ajax to observableArray

I want to push data from ajax to knockout observableArray , but it give me an error:

The argument passed when initializing an observable array must be an array, or null, or undefined.

 efine(['uiComponent', 'ko', 'jquery'], function (Component, ko, jquery) { return Component.extend({ initialize: function () { this._super(); /* State and cities */ this.selectCity(); }, selectCity: function () { var myViewModel = {}; state = ko.observableArray([]); jquery.ajax({ url: 'http://127.0.0.1/magento/hamechio/region.php', type: "GET", dataType: "json", success: function(data) { myViewModel = data; state.push(data); } }); console.log(state); } }); }); 

this line should be change as per my knowledge.

 state = ko.observableArray([]);

to this

var state = ko.observableArray();

This is a ajax scope ques.

you can use 'var'.

like this:

var state = ko.observableArray([]);

Can I suggest looking through the Documentation that has lots of working examples: https://knockoutjs.com/documentation/observableArrays.html

Firstly, your View Model is the object on which all of your programme is built on. This object contains all of the data to show (as knockout observable property "methods") and commands to receive (functions). Therefore you need to define the view model to contain everything your application needs to do:

var viewModel = {
    //Bindings
    state = ko.observableArray();
}

Now you can write to the viewModel.state() :

if data is an array and you don't want to track changes to data's items:

viewModel.state(data);

or push them one at a time:

data.foreach(function(el){ viewModel.state.push(el); });

If you want to track changes to each individual item's properties, you will need to use the second method and convert each element into an object composed of ko.observable s.

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