我已填充了一个下拉列表,其中包含页面加载的值,如here所示。然后根据下拉列表的选定值,我需要从服务器获取数据并填充另一个下拉列表。
我尝试了here也在下面的代码中显示,但它不起作用:
Html代码:
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice, optionsCaption: 'Choose..', event: {change: getstates}"></select>
<br/>
<label data-bind="text: selectedChoice"></label>
<select data-bind="options: states, optionsText: 'name', optionsValue: 'id', value: selectedstate, optionsCaption: 'Choose..'"></select>
<label data-bind="text: selectedState"></label>
JS代码:
var states1 = [
{"id": "1", "name": "state1"},
{"id": "2", "name": "state2"}];
var CountryModel = function(data){
var self = this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
};
var StateModel = function(data){
var self = this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
};
var viewModel = function(data) {
var self = this;
self.selectedChoice = ko.observable();
self.selectedstate=ko.observable();
self.countries = ko.observableArray([
new CountryModel({id: "1", name: "Russia"}),
new CountryModel({id: "2", name: "Qatar"})]);
self.states = ko.observableArray([]);
self.getstates== function(data) {
self.states(ko.mapping.fromJS(states1)());
};
};
ko.applyBindings(new viewModel());
真心感谢任何帮助。
由于
答案 0 :(得分:0)
self.getStates
而不是等于运算符=
来分配 ==
:
self.getstates = function(data) {
self.states(ko.mapping.fromJS(states1)());
};
您选择的州标签存在问题。 JavaScript区分大小写,因此selectedState
与selectedstate
不同。由于您在视图模型中将其声明为selectedstate
,因此必须使用:
<label data-bind="text: selectedstate"></label>
另外,为了使用ko.mapping
,您需要在此处添加映射插件:https://github.com/SteveSanderson/knockout.mapping。我刚从cdnjs.com为我的jsfiddle添加了它:http://cdnjs.com/libraries/knockout.mapping