2016-01-22 102 views
0

[{"uniqueId":61,"content":"test","createTextDate":"time"}]骨幹收集從URL的JSON

這是/data/commentList.json

var Comment = Backbone.Model.extend({ 
    defaults: { 
     uniqueId: null, 
     createTextDate: null, 
     content: null 
    } 
}); 

模型骨幹收集

var List = Backbone.Collection.extend({ 
    model: Comment, 

    url: function() { 
     return '/data/commentList.json'; 
     },  

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

骨幹收集

var ListView = Backbone.View.extend({ 
    el: $('#test'), 
    initialize: function() { 
     _.bindAll(this, 'render'); 
     this.collection = new List(); 
     this.render(); 
    }, 
    render: function() { 
     var self = this; 
     this.collection.fetch({ 
      success: function() { 
       console.log("SUCESS"); 
       console.log(that.collection.toJSON()); 
      }, 
      error: function() { 
       console.log('Failed to fetch!'); 
      } 
     }); 
    } 
}); 

控制檯登錄

Failed to fetch!

如何使用JSON的網址,使骨幹收藏?

+0

你爲什麼需要'parse'和'sync'? – Muhaimin

+0

@MuhaiminAbdul從url – Namjug

+0

獲取json將自動識別它。它是準備好的。無需解析它 – Muhaimin

回答

2
parse: function(response) { 
     return response.results; 
    }, 

上面的代碼假定您的服務器返回

{"results": [comment1, comment2]} 

你很少需要重寫sync方法。