2012-10-25 56 views
1

我試圖用backbones.js獲取從Twitter搜索如何獲得與Backbone.js的

得到JSON 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);​ 

我剛開始接觸骨幹,我只是想CONSOLE.LOG的JSON

,你可以在這裏看到我的例子。 jsfiddle.net/YnJ9q/2/

回答

5

有兩個問題上面:

首先,你需要添加一個成功/以失敗回調的獲取方法,讓你有取出的JSON登錄到控制檯。 。

getPost: function(){ 
    var that = this; 
    this.collection.fetch(
    { 
     success: function() { 
      console.log(that.collection.toJSON()); 
     }, 
     error: function() { 
      console.log('Failed to fetch!'); 
     } 
    }); 
} 

的另一個問題是「同源策略」的問題,你可以找到如何解決,通過採取一看this link

更新: 我修改你的代碼,包括更新sync方法現在它Take a look here!

基本上,更新您的collection到包括parsesync方法如下:!

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); 
    } 
}); 
+0

感謝這真的很難讓我的頭腦在backbone.js希望它的價值最終將堅持下去。試圖獲得側邊欄點擊返回鳴叫此刻 – user1503606

+0

嘿amulya我不明白的是如何說我想有一個輸入框來運行搜索的網址如何設置變量在jquery我會做「http:///search.twitter.com/search.json?q="+query+「」http://jsfiddle.net/isimpledesign/BHrmC/1/我不明白這是怎麼做的主幹? – user1503606

+1

看看這裏:http://jsfiddle.net/BHrmC/2/ –