我使用映射插件来更新视图模型,如下所示:
$.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) {
if (json.Page == 1) {
ko.mapping.fromJS(json, {}, self);
} else {
self.List().push(ko.mapping.fromJS(json.List));
}
console.log(ko.toJSON(self.List()));
},
});
然而,不是更新List()可观察数组(在ajax调用完成时仅添加NEW项目 - 对于第2页(来自DB的下一个项目),它会添加一个新的List =>注意" [&# 34;控制台输出中的元素:
AJAX响应(json)
{" DiscountType":"事务处理""列表":[{" ActivationDate":" /日期(1427215761818 )/","客户名称":"另外两个2"," CustomerNumber":4328,"百分比":20,& #34; HasDiscount":真},{" ActivationDate":" /日期(1428079761818)/""客户名称":"另一树"" CUSTOMERNUMBER":1212,"百分比":20," HasDiscount":真}],"页":2 }
控制台输出:
[{" ActivationDate":" / Date(1388556000000)/"," CustomerName":" Test1 Inc.", " CUSTOMERNUMBER":10032"百分比":20," HasDiscount":真},{" ActivationDate":" /日期(1426783761818)/","客户名称":"另一个1"," CustomerNumber":5174,"百分比":20 " HasDiscount":真},[{" ActivationDate":" /日期(1427215761818)/""客户名称":&# 34;另外两个2"," CustomerNumber":4328,"百分比":20," HasDiscount":true},{" ActivationDate&# 34;:" /日期(1428079761818)/","客户名称":"另一棵树"," CustomerNumber":1212,&# 34;百分比":20," HasDiscount":真}]]
我做错了什么?
答案 0 :(得分:1)
要推送返回数组的各个元素,请执行类似
的操作success: function (json) {
if (json.Page == 1) {
ko.mapping.fromJS(json, {}, self);
}
else {
json.List.forEach(
function(element) {
self.List.push( ko.mapping.fromJS(element) );
} );
}
console.log(ko.toJSON(self.List()));
}
var vm = function() {
var self = this;
self.List = ko.observableArray([]);
self.initiate = function() {
json = JSON.parse('{"DiscountType":"Transaction","List":[{"ActivationDate":"/Date(1427215761818)/","CustomerName":"Another two 2","CustomerNumber":4328,"Percent":20,"HasDiscount":true},{"ActivationDate":"/Date(1428079761818)/","CustomerName":"Another tree","CustomerNumber":1212,"Percent":20,"HasDiscount":true}],"Page":2}');
json.List.forEach(function(entry) {
self.List.push(ko.mapping.fromJS(entry));
});
};
};
vm = new vm();
ko.applyBindings(vm);
vm.initiate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js'></script>
<html>
<div data-bind='foreach: List'>
<div data-bind='text: ActivationDate'></div>
</div>
</html>