获取成功方法不触发,仅显示'parsererror',但浏览器接收数据

时间:2016-03-23 18:04:11

标签: json backbone.js fetch

我有两个集合,我的BlueCollection可以很好地从存储在变量中的数组中加载数据,但是我的RedCollection在从不使用变量的不同数组中获取数据时遇到了一些问题。我错过了什么吗?

jsFiddle here

BlueCollection = Backbone.Collection.extend({
  model: BlueModel,
});

RedCollection = Backbone.Collection.extend({
  model: RedModel,
  url: 'data/data.json' // It is from http://www.localhost:3000/data/data.json
});

BlueCollection在加载此数据时没有问题。

var blue = [
  {id: 1, title: 'blue 1 - '},
  {id: 2, title: 'blue 2 - '},
  {id: 3, title: 'blue 3'}
];

但RedCollection在获取此数据时遇到问题

// http://www.localhost:3000/data/data.json
[
  {id: 1, title: 'red 1 - '},
  {id: 2, title: 'red 2 - '},
  {id: 3, title: 'red 3'}
]  

然而,当我检查firebug时,我看到浏览器接收到数据,但是fetch success方法永远不会触发,只有complete方法触发消息parsererror Backbone fetch response

完整的代码是:

var blue = [
    {id: 1, title: 'blue 1 - '},
  {id: 2, title: 'blue 2 - '},
  {id: 3, title: 'blue 3'}
];

// http://www.localhost:3000/data/data.json
/* No variable, this json should be fetched from RedCollection
[
    {id: 1, title: 'red 1 - '},
  {id: 2, title: 'red 2 - '},
  {id: 3, title: 'red 3'}
]
*/

BlueModel = Backbone.Model.extend({});
RedModel = Backbone.Model.extend({});

BlueCollection = Backbone.Collection.extend({
  model: BlueModel,
});

RedCollection = Backbone.Collection.extend({
  model: RedModel,
  url: 'http://www.localhost:3000/data/data.json'
  /* 
        [
            {id: 1, title: 'red 1'},
        {id: 2, title: 'red 2'},
        {id: 3, title: 'red 3'}
        ]
    */
});

BlueView = Backbone.View.extend({
  initialize: function() {
    this.collection = new BlueCollection(blue);
    this.render();
  },

  render: function() {
    var self = this;
    _.each(this.collection.models, function(item) {
        self.addAll(item);
    }, this);
  },

  addAll: function(item) {
    $('#blue').append(item.get('title'));
  }
});

RedView = Backbone.View.extend({
  initialize: function() {
    this.collection = new RedCollection; 

    this.collection.fetch({ 
            success: function () {
            console.log('Success'); // Never shows, but console shows content loaded
          },
          error: function(xhr, textStatus) {
                console.log(xhr);
            },  
          complete: function(xhr, textStatus) {
                console.log(textStatus); // Only this log shows with: parsererror
            }
        });
    this.render();
  },

  render: function() {
    var self = this;

    _.each(this.collection.models, function(item) {
        self.addAll(item);
    }, this);
  },

  addAll: function(item) {
    $('#red').append(item.get('title'));
  }
});

blueview = new BlueView;
redview = new RedView;

1 个答案:

答案 0 :(得分:1)

我记得json属性必须在""内。像这样修改json:

[
  {"id": 1, "title": "red 1 - "},
  {"id": 2, "title": "red 2 - "},
  {"id": 3, "title": "red 3"}
]