【发布时间】:2017-05-04 22:58:08
【问题描述】:
创建了一个演示问题的 JSBin:http://jsbin.com/kukehoj/1/edit?html,js,console,output
我正在创建我的第一个基于 REST 的网站。后端使用 Python(Django REST 框架),似乎工作正常。我试图让前端获得帖子的 cmets,但它不起作用。
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>
scripts.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,但我删除了不相关的部分)
一切正常,除了 cmets 似乎格式错误。
chrome 控制台显示绑定到每个评论对象值的 JSON“responseText”。
如果这是一个愚蠢的问题,我很抱歉,但我已经尝试了所有方法 - 但它不起作用。 (我是菜鸟)
【问题讨论】:
-
错误的格式是什么样的?
-
添加了截图
标签: python json django rest knockout.js