创建了一个 JSBin 来演示该问题:http://jsbin.com/kukehoj/1/edit?html,js,console,output
我正在创建我的第一个由 REST 驱动的网站。后端采用 Python(Django REST Framework),并且似乎工作正常。我试图让前端获取帖子的评论,但它不起作用。
HTML 导入
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script>
脚本.js
function Comment(data) {
this.body = ko.observable(data.responseText)
}
function Post(data) {
this.title = ko.observable(data.title)
this.body = ko.observable(data.body)
var self = this;
self.comments = ko.observableArray([])
self.comments(($.map(data.comments, function(link) { // Map the data from
return $.getJSON(link, function(data) { return new Comment(data)}) //These requests
})))
}
function PostViewModel() {
// Data
var self = this;
self.posts = ko.observableArray([])
// Get the posts and map them to a mappedData array.
$.getJSON("/router/post/?format=json", function(allData) {
var mappedData = $.map(allData, function(data) { return new Post(data)})
self.posts(mappedData)
})
}
ko.applyBindings(new PostViewModel());
服务器数据:
[{ "title":"-->Title here<--",
"body":"-->Body here<--",
"comments":[
"http://127.0.0.1:8000/router/comment/6/?format=json",
"http://127.0.0.1:8000/router/comment/7/?format=json",
"http://127.0.0.1:8000/router/comment/8/?format=json",
"http://127.0.0.1:8000/router/comment/9/?format=json"]
}]
每个链接指向:
{"body":"-->Body here<--"}
index.html
<div class="col-lg-7" data-bind="foreach: { data: posts, as: 'posts' }">
<h3 data-bind="text: title"></h3>
<p data-bind="text: body"> </p>
<span data-bind="foreach: { data: comments(), as: 'comments' }">
<p data-bind="text: comments.body"></p>
</span>
</div>
(还有很多 HTML,但我删除了不相关的部分)
一切工作正常,除了评论似乎格式错误。
Chrome 控制台显示绑定(bind)到每个评论对象值的 JSON“responseText”。
如果这是一个愚蠢的问题,我很抱歉,但我已经尝试了一切 - 但它不起作用。 (我是菜鸟)
最佳答案
除了您提供的部分 this.body = ko.observable(data.responseText)
之外,您提供的示例代码没有任何问题。而您的数据不包含responseText
在您的样本中commentData
目的 。如果你替换 commentData
对象 var commentData = {"responseText":"-->Body here<--"}
它有效。
注意:这部分
<span data-bind="foreach: { data: comments(), as: 'comments' }">
<p data-bind="text: comments.body"></p> // comments.body => body
</span>
你的问题是错误的,但你的示例代码是正确的。它应该是
<span data-bind="foreach: { data: comments(), as: 'comments' }">
<p data-bind="text: body"></p>
</span>
这是示例的工作版本:https://jsfiddle.net/rnhkv840/26/
关于python - KO : Error when parsing JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41230251/