我有以下HTML代码。我将数据绑定到标签。
data-bind="text: employeeData.Id, valueUpdate:'keyup'"
data-bind="text: employeeData.Name, valueUpdate:'keyup'"
我的淘汰剧本如下:
self.employeeData = { Id: ko.observable(" "),Name:ko.observable(" ") };
self.getEmployee = function(data, event){
$.ajax({
type: "Get",
url: 'http://localhost:8081/api/Values/GetEmployee',
dataType: "json",
cache: false,
async: false,
crossDomain:true,
dataType : 'json',
success: function (data) {
self.employeeData = ko.observable(data);
},
error: function () {
alert("Error");
}
});
我正在从Ajax调用中获取数据,但它没有绑定到UI。谁能帮助我,我在这里做错了什么?
答案 0 :(得分:1)
您的employeeData
属性不是 observable ,因此当ajax success
处理程序运行时(可能在applyBindings
运行之后),该属性将被覆盖参考一个可观察的。
做这样的事情:
function getEmployee(data) {
data = data || {};
return {
Id: ko.observable(data.Id || " "),
Name: ko.observable(data.Name || " ")
};
}
self.employeeData = ko.observable(getEmployee());
self.getEmployee = function(data, event){
$.ajax({
type: "Get",
url: 'http://localhost:8081/api/Values/GetEmployee',
success: function (data) {
// option 1:
self.employeeData(getEmployee(data));
// option 2:
self.employeeData().Id(data.Id);
self.employeeData().Name(data.Name);
// option 3:
// use ko.mapping library and its update functionality
// option 4:
// use constructor functions and give them a "loadData" method, for ex.
}
}
});
我建议查看"构造函数"对于视图模型,以及ko.mapping插件。