级联下拉列表没有在页面加载淘汰赛js上获得完整数据

Cascading dropdownlist without geting complete data on page load knockoutjs

我已经用页面加载时的值填充了一个下拉列表,如图 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());

真诚感谢任何帮助..

谢谢

self.getStates 必须使用赋值运算符 = 而不是相等运算符 ==:

进行赋值
self.getstates = function(data) {
    self.states(ko.mapping.fromJS(states1)());
};

您选择的州标签有问题。 JavaScript 区分大小写,因此 selectedStateselectedstate 不同。由于您在视图模型中将其声明为 selectedstate,因此您必须使用它:

<label data-bind="text: selectedstate"></label>

此外,为了使用 ko.mapping,您需要从此处包含映射插件:https://github.com/SteveSanderson/knockout.mapping. I just added it from cdnjs.com for my jsfiddle: http://cdnjs.com/libraries/knockout.mapping

JsFiddle