我正在尝试使用backbones.js fetch从twitter搜索中获取json
我的代码可以告诉我哪里出错了?
(function($){
var Item = Backbone.Model.extend();
var List = Backbone.Collection.extend({
model: Item,
url:"http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&result_type=mixed"
});
var ListView = Backbone.View.extend({
el: $('#test'),
events: {
'click button#add': 'getPost'
},
initialize: function(){
_.bindAll(this, 'render', 'getPost');
this.collection = new List();
this.render();
},
render: function(){
var self = this;
$(this.el).append("<button id='add'>get</button>");
},
getPost: function(){
console.log(this.collection.fetch());
}
});
// **listView instance**: Instantiate main app view.
var listView = new ListView();
})(jQuery);?
Run Code Online (Sandbox Code Playgroud)
我刚刚开始使用骨干,我只想在console.log中使用json
你可以在这看到我的例子.jsfiddle.net/YnJ9q/2/
上面有两个问题:
首先,您需要向fetch方法添加成功/失败回调,以便将获取的JSON记录到控制台.
getPost: function(){
var that = this;
this.collection.fetch(
{
success: function () {
console.log(that.collection.toJSON());
},
error: function() {
console.log('Failed to fetch!');
}
});
}
Run Code Online (Sandbox Code Playgroud)
另一个问题是"同源政策"问题.您可以通过查看此链接了解如何解决这个问题.
更新:
我修改了您的代码并包含更新的sync方法.它现在有效!看看这里!
基本上,更新您collection的包括parse和sync方法如下:
var List = Backbone.Collection.extend({
model: Item,
url: "http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&result_type=mixed",
parse: function(response) {
return response.results;
},
sync: function(method, model, options) {
var that = this;
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: that.url,
processData: false
}, options);
return $.ajax(params);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9807 次 |
| 最近记录: |