简体   繁体   English

从ajax提取数据到observableArray

[英]knockout push data from ajax to observableArray

I want to push data from ajax to knockout observableArray , but it give me an error: 我想将数据从ajax推送到淘汰的observableArray,但这给了我一个错误:

The argument passed when initializing an observable array must be an array, or null, or undefined. 初始化可观察数组时传递的参数必须是数组,为null或未定义。

 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. 这是一个ajax作用域查询。

you can use 'var'. 您可以使用“ 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 我是否可以建议阅读包含大量工作示例的文档: 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() : 现在,您可以写入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. 如果要跟踪对每个项目的属性的更改,则需要使用第二种方法,并将每个元素转换为由ko.observable组成的对象。

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

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