我正在使用 Backbone.js 构建一个评论对象。集合中的 URL 返回如下所示的 json:
{'type': 'comment',
'data': [{"body": "commment number 1!",
"create_dt": 1343166264000,
"comment_id": 1, "depth": 0,
"user": {"sid": "1",
"uid": "1",
"name": "Amie C",
"level": "2"},
"sid": 1
},
{"body": "commment number 1-1!",
"create_dt": 1343166361000,
"comment_id": 4,
"depth": 1,
"user": {"sid": "1",
"uid": "1",
"name": "lila M",
"level": "2"},
"sid": 1}
}]
}
该网址在浏览器中有效,我能够看到我所有的 json 都回来了。但是,我遇到的问题是加载comment.js 时没有数据返回。我会看到一个红色但显示 200 OK 并且响应中没有正文的 Get 请求。我的模型的长度也是0。
非常感谢先进。
这是comment.js:
//default comment model
var Comment = Backbone.Model.extend({
defaults: {
body: "",
create_dt: null,
comment_id: null,
depth: null,
user: null,
sid: null
}
});
//instaitiate a new comment
var comment = new Comment;
//default event view
var CommentView = Backbone.View.extend({
tagName: "li",
className: "comment",
initialize: function(){
this.render();
},
render: function(){
$(this.el).html(this.model.toJSON());
return this;
}
});
//default comments collection
var Comments = Backbone.Collection.extend({
model: Comment,
initialize: function(){
},
url:"http://127.0.0.1/test/objects/json/comments.json",
parse: function(resp) {
return resp.data;
}
});
//default eventsview for events collection's view
var CommentsView = Backbone.View.extend({
tagName: "ul",
className:"comments",
intialize: function(){
this.render();
},
render: function(){
_.each(this.collection.models, function(comment){
//init the CommentView and passed in its model here
var commentView = new CommentView({model: comment});
$(this.el).prepend(commentView.render().el)
}, this);
return this;
}
});
//instantiate new events collection
var comments = new Comments;
var commentsView = new CommentsView({collection: comments});
//on the new events collection, we fetch the data from URL
comments.fetch({
error:function(response, xhr){
console.log(response);
console.log(xhr)
},
success:function(){
console.log("success");
$('.comments_container').html(commentsView.render().el);
}
});
html看起来像这样:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Share</title>
<link rel="stylesheet" href="share.css" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script src="js/comment.js"></script>
</head>
<body>
<div class="main_app">
<div class="comments_container"></div>
</div>
</body>
</html>