我正在尝试使用 Knockout.js 做一些级联下拉菜单在我定义视图模型之后,我有以下代码,但 $.getJSON 没有启动。请帮忙。这是进行级联下拉的正确方法吗?谢谢。
$(function () {
$.getJSON('http://my.comapny/webapi/facility/',
null, function (response) {
viewModel.facilities(response);
});
ko.applyBindings(new viewModel());
});
这是cshtml:
@section scripts{
<script>
function vm() {
var self = this;
self.facility = ko.observable();
self.facilities = ko.observableArray();
self.service = ko.observable();
self.services = ko.observableArray();
self.role = ko.observable();
self.roles = ko.observableArray();
self.result = ko.observable();
self.facilitySelect = ko.computed({
read: self.facility,
write: function (facility) {
self.facility(facility);
$.getJSON('http://my.comapny/webapi/service/' + self.facility.value,
null, function (response) {
self.services(response);
});
},
owner: self
});
self.serviceSelect = ko.computed({
read: self.service,
write: function (service) {
self.service(service);
$.getJSON('http://my.comapny/webapi/role' +
'?facilityId=' + self.facility.value + '&serviceId=' + self.service.value,
null, function (response) {
self.roles(response);
});
},
owner: self
});
self.result = ko.computed(function () {
var result = '';
result += self.facility() != undefined ? 'Facility: ' + self.facility().text + ', ' : '';
result += self.service() != undefined ? 'Service: ' + self.service().text + ', ' : '';
result += self.role() != undefined ? 'Role: ' + self.role().text : '';
return result;
}, self);
}
$(function () {
$.getJSON('http://my.comapny/webapi/facility/',
null, function (response) {
vm.facilities(response);
});
ko.applyBindings(new vm());
});
</script>
}
<h1>Knockout js cascading dropdown example</h1>
<select data-bind="options: facilities, optionsCaption: 'Choose facility...',
optionsValue: function (item) { return item.value; },
optionsText: function (item) { return item.text; }, value: facilitySelect,
valueUpdate: 'change'"
id="facility" name="facility">
</select>
<select data-bind="options: services, optionsCaption: 'Choose service...',
optionsValue: function (item) { return item.value; },
optionsText: function (item) { return item.text; }, value: serviceSelect,
valueUpdate: 'change'"
id="service" name="service">
</select>
<select data-bind="options: roles, optionsCaption: 'Choose role...',
optionsValue: function (item) { return item.value; },
optionsText: function (item) { return item.text; }, value: role,
valueUpdate: 'change'"
id="role" name="role">
</select>
<span data-bind="text: result"></span>