我正在尝试使用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>
答案 0 :(得分:0)
你拼错了你的网址吗?
这是:http://my.comapny/webapi/facility/
原来是这样的:http://my.company/webapi/facility/
我建议您将构造函数从vm
重命名为ViewModel
,因为我相信这会让您感到困惑,认为vm
是ViewModel的一个实例而不是构造函数功能
function ViewModel () { ... }
var vm = new ViewModel();
ko.applyBindings(vm);
// Later...
vm.facilities(response);