Knockout JS数组为空或可以't检索值
Knockout JS array empty or can't retrieve values?
我有一个Javascript ajax函数,可以从服务器检索评论(注意:我是Knockout JS的新手):
function Comments() {
var self = this;
self.commentArray = ko.observableArray();
self.getNewerComments = function(lastCommentId) {
pageId = $('body').attr('id');
$.ajax({
type: "GET",
dataType: "json",
url: "Controller/getNewerComments/" + pageId + "/" + lastCommentId,
})
.done(function(data) {
self.commentArray = ko.observableArray(data);
alert(self.commentArray[0].authorName);
})
}
}
通过警报,我可以看到该值确实设置在那里,在我的JS文件的开头,我有以下代码:
var comments = new Comments();
ko.applyBindings(comments);
comments.getNewerComments(0);
在html文件中:
<!-- ko foreach: commentArray -->
<li>Item <span data-bind="text: $index"></span></li>
<!-- /ko -->
</div>
但是,html文档中没有显示任何内容,甚至"Item"文本也没有显示,这表明数组的长度为0。这里有什么问题?为什么我不能使用数组值
谢谢。
您应该使用现有的可观察数组(已绑定),而不是创建新的数组:
.done(function(data) {
self.commentArray(data);
alert(self.commentArray[0].authorName);
})
您设置了两次可观察数组。在开始和Ajax调用时。一旦您构建了模型并应用了绑定,就不需要再麻烦可观测性了。它完成了。将处理对绑定到模型的数据对象的任何更改。
相关文章:
- 将大数组(字符串和类型数组的混合物)存储到blob或文件中/从blob或文件检索大数组的最佳方式
- 从Meteor中的数组中检索字符串
- 在主要的JavaScript引擎中,在JavaScript关联数组(动态对象属性)中检索/插入的复杂性是多少
- 在 ajax 成功和循环 json 数组时检索 json 数组
- 如何从 Angular ng-repeat 指令中检索数组中的某些索引
- 如何使用javascript中的for循环成对检索数组元素
- 从 json 字符串中检索数组值
- 如何使用 d3 从 javascript 中的 csv 文件中检索数组
- 如何在 javascript 中检索数组中相同值的数量
- Javascript 数组未获得总和.而不是检索数组本身
- 检索数组和输出结果以生成一组html图像
- 检索数组数据从JQuery Ajax函数到javascript
- 检索数组的索引
- 如何检索数组的元素作为对象属性
- Javascript,检索数组名
- 使用PFQuery检索数组中包含特定项的pfininstallation对象
- 如何检索数组的数据arrMyLatLng函数
- 无法在js中检索数组数据
- 正在从本地存储检索数组中对象的值
- 在$http上检索数组并在离子列表的离子项目中查看