被 javascipt 的 knockout 库困住了。 所以,我想实现一个简单的论坛。我有一个带有两个 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 请求的这一部分:
js.posts(postres);
在您拉取帖子的第二个 json 请求的回调之前执行。您必须更改它,以便在执行 js.posts(postres);
之前填充 posts 数组。 ,例如像这样:
$.getJSON("http://someadress/posts/" + js.id, function(postdata) {
$.each(postdata, function(idx, post){
var jspost = jQuery.parseJSON(post);
postres.push(jspost);
})
js.posts(postres);
})
关于javascript - Knockout 没有使用我的数据渲染模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34597287/