我尝试获取此服务器:http://cshosting.webfactional.com/api/v1/projects/?format=json 到backbone.js集合。 然后我尝试console.log它,但它不起作用。 对我来说非常重要,请帮助。
新闻:我发现它与JSONP有关。很高兴听到更多相关信息。感谢。
这是我的代码的一部分:
window.ProjectList = Backbone.Collection.extend({
model: Project,
url:"http://cshosting.webfactional.com/api/v1/projects",
parse: function(response) {
return response.objects;
}
});
另一部分:
window.HomeView = Backbone.View.extend({
initialize:function () {
this.projectList = new ProjectList();
this.projectList.fetch({success : function() {console.log(this.projectList); }});
this.homeListView = new HomeListView({model: this.projectList});
}
});
答案 0 :(得分:1)
this
回调中的fetch
不会引用您的HomeView
实例。尝试使用另一个变量来确保引用所需的对象。
initialize:function () {
var self = this;
this.projectList = new ProjectList();
this.projectList.fetch({success : function() {console.log(self.projectList); }});
this.homeListView = new HomeListView({model: this.projectList});
}
如果这不能解决问题,请说明会发生什么。使用webkit检查器的网络选项卡确保调用正确的GET请求和响应。确保调用parse
函数,response
对象符合您的预期。
答案 1 :(得分:0)
看起来你想要做更像这样的事情:
window.Project = Backbone.Model.extend({
url:"http://cshosting.webfactional.com/api/v1/projects/?format=json"
});
window.ProjectList = Backbone.Collection.extend({
model: Project,
url:"http://cshosting.webfactional.com/api/v1/projects/?format=json"
});
window.HomeView = Backbone.View.extend({
initialize:function () {
_.bindAll(this, 'render');
},
render: function(){
var self = this;
console.log(self.collection);
return this;
}
});
var project = new Project();
var collection = new ProjectList();
collection.fetch({
success: function(result_collection, resp) {
var view = new HomeView ({ collection: result_collection });
view.render();
}
});