Backbone从Json获取数据

时间:2016-06-27 12:33:36

标签: javascript backbone.js

我是Backbone的新手。我试图从骨干网中的json获取数据。但它没有获取数据。在尝试获取数据时进入错误功能。这是我的代码:

var Item = Backbone.Model.extend();
var List = Backbone.Collection.extend({
    model: Item,

    url: "form.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: $('.deep-div'),
    events: {
        'click button#add': 'getPost'
    },
    initialize: function() {
        _.bindAll(this, 'getPost');
        this.collection = new List();
        this.getPost();
    },
    getPost: function() {
        var that = this;
        this.collection.fetch({
            success: function() {
                console.log(that.collection.toJSON());
            },
            error: function() {
                console.log('Failed to fetch!');
            }
        });
    }
});
var listView = new ListView();

我的json

{
    "status": "SUCCESS",
    "statusMessage": "",
    "payload": [
        {
            "type": "text",
            "label": "Name",
            "currentValue": " ",
            "isRequired": "true"

        },
        {
            "type": "Date",
            "label": "DOB",
            "currentValue": " ",
            "isRequired": "true"
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

如果不知道自己在做什么,请不要覆盖sync方法。

如果JSON文件的路径正确,并且您通过HTTP服务器为应用程序提供服务并且没有文件访问权限问题,则以下内容将起作用。

var List = Backbone.Collection.extend({
  model: Item,
  url: "form.json",
  parse: function(response) {
    return response.payload;
  }
});