【发布时间】:2016-04-08 10:16:12
【问题描述】:
卡在 javascipt 的淘汰赛库中。 所以,我想实现简单的论坛。我有两个 ajax 请求的 javascript 文件,用于主题和帖子。我有 html 模板。
function dealModel() {
var self = this;
self.board = ko.observableArray([]);
var res = [];
$.getJSON("http://someaddress/threads", function(data) {
$.each(data, function(i, thread) {
var js = jQuery.parseJSON(thread);
js.posts = ko.observableArray([]);
var postres = []
$.getJSON("http://someadress/posts/" + js.id, function(postdata) {
$.each(postdata, function(idx, post){
var jspost = jQuery.parseJSON(post);
postres.push(jspost);
})
})
js.posts(postres);
res.push(js);
})
self.board(res);
})
}
$(document).ready(function(){
ko.applyBindings(new dealModel());
});
var testdata = [{text : "text 1"} , {text : "text2"}]
这是我的 js 代码。它完美地适用于主题,但是当我发布我的帖子时,我的可观察数组“帖子”已经为空。 对于测试,我创建了测试数组“testdata”(如下),并传入我的可观察数组。而且,javascript 可以完美运行。 这是我的模板
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
<script type="text/javascript" src="ajaxknockout.js"></script>
</head>
<body>
<div class='board'>
<div class='threads' data-bind="foreach: board">
<p data-bind="text: title"></p>
<div class= "posts" data-bind="foreach: $data.posts">
<p data-bind="text: text"> </p>
</div>
</div>
</div>
</body>>
</html>
所以,我认为我的帖子 JSON 有问题。 在这里。
["{\"createTime\": \"Monday, 04. January 2016 05:53PM\",\"thread_id\": \"2\",\"text\": \"post 1\",\"id\": \"4\"}", "{\"createTime\": \"Monday, 04. January 2016 05:53PM\",\"thread_id\": \"2\",\"text\": \"post 2\",\"id\": \"5\"}", "{\"createTime\": \"Monday, 04. January 2016 05:53PM\",\"thread_id\": \"2\",\"text\": \"post 3\",\"id\": \"6\"}"]
所以,我有一个问题。我的代码有什么问题?为什么knockout理解我的测试数据,却完全拒绝生产数据?
【问题讨论】:
-
看起来您的 JSON 包含字符串数组而不是对象数组。您必须检查 JSON 在服务器端是如何形成和存储的。
-
@f_martinez, ,你能给我一个正确的 json 数组的例子吗?我在我的 json 中没有看到任何错误
-
你的 json 没问题。我刚刚注意到您将
parseJSON应用于每个项目。实际上,尼古拉下面提供的答案是正确的。
标签: javascript arrays json templates knockout.js