剔除JS数组为空或无法检索值? [英] Knockout JS array empty or can't retrieve values?

查看:107
本文介绍了剔除JS数组为空或无法检索值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Javascript Ajax函数,可从服务器检索注释(注意:我是Knockout JS的新手):

I have a Javascript ajax function that retrieves comments from the server(Note: I'm new to 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文件的开头,我有以下代码:

With the alert I can see that the value is indeed set there, at the start of my JS file I have the following code:

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. 这是什么问题?为什么我不能使用数组值?

However, nothing shows up in the html document, not even the "Item" text, which indicates the array has 0 length. What's the problem here? Why can't I use the array values?

谢谢.

推荐答案

您应该使用现有的可观察数组(已绑定),而不是创建一个新数组:

You should use existing observable array (which was bound) instead of creating a new one:

.done(function(data) {
   self.commentArray(data);
   alert(self.commentArray[0].authorName);
 })

这篇关于剔除JS数组为空或无法检索值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆