使用 knockout 和 jquery ajax 填充下拉列表

Populating a dropdown list using knockout and jquery ajax

我正在使用 ajax 填充下拉列表。

    var getCertifications = function () {
    $.getJSON("/Provider/GetCertifications", function (data) {
        $.each(data, function (i, item) {
            var certification_data = "<option value=" + item.CertificationID + ">" + item.Certification + "</option>";
            $(certification_data).appendTo("#certification");
          });
      });
   };

正在 document.ready 方法中调用 getCertifications。 我想根据第一个选择选项的值填充第二个下拉列表 dropdownlist.So 我写了另一个函数

 var getSpecializations = function () {
var value = $("#certification").val();
$.getJSON("/Provider/GetSpecializations/", { certificationID: value }, function (data) {
    $.each(data, function (i, item) {
        var specialization_data = "<option value=" + item.SpecializationId + ">" + item.Specialization + "</option>";
        $(specialization_data).appendTo("#specialization");
          });
      });
  }

html如图

  <div class="form-group">
            <label class="col-sm-2 control-label labelfont">Certification: </label>
            <div class="col-sm-6">
                <select class="form-control" id="certification",name="certification",data-bind="value: certification" >
                    <option value="0">Select a Certification</option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label labelfont">Specialization:</label>
            <div class="col-sm-6">
                <select class="form-control" id="specialization" , name="specialization" data-bind="value: specialization" >
                    <option value="0">Select a Specialization</option>
                </select>
            </div>
        </div>

我的视图模型具有如图所示的可观察对象

self.certification = ko.observable("");
self.specialization = ko.observable("");

我像这样在第一个下拉列表的订阅方法中调用 getSpecializations 函数

self.certification.subscribe(function () { 
    getSpecializations();      
});

控制台中没有错误,但第二个下拉即;专业化下拉列表没有 populated.Could 你们给我指出了正确的方向。

好吧,你需要这样做

查看:

<select data-bind="options:specializationArray,optionsText:'Specialization',optionsValue:'SpecializationId',value:specialization" />

ViewModel:

 var getSpecializations = function () {
var value = self.
$.getJSON("/Provider/GetSpecializations/", { certificationID: value }, function (data) {
   self.specializationArray(data) //array with Specialization and SpecializationId
  }

工作fiddlehere