0

I am newbie to Backbone. I am trying to fetch data from json in backbone.But its not getting the data. going in error function when trying to fetch the data.Here's my code:

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

And my json is

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

        },
        {
            "type": "Date",
            "label": "DOB",
            "currentValue": " ",
            "isRequired": "true"
        }
    ]
}
Master.Deep
  • 792
  • 5
  • 20

1 Answers1

0

Do not override the sync method without knowing what you're doing.

Simply the following will work given that the path to JSON file is correct, and you're serving the application via an HTTP server and there is no file access permission issues.

var List = Backbone.Collection.extend({
  model: Item,
  url: "form.json",
  parse: function(response) {
    return response.payload;
  }
});
T J
  • 42,762
  • 13
  • 83
  • 138
  • Got It Thanks.. Now can you tell me when to override Sync. As there can be possibilities of my json to come from cross origin domain. – Master.Deep Jun 28 '16 at 05:27
  • @Master.Deep `sync` is overridden to change the way all methods like `fetch`, `save`, `destroy` etc interact with persistence layer. For JSONP just pass the options to fetch call http://stackoverflow.com/a/9996420/2333214, or override fetch method alone , not entire `sync`. By the way implementing CORS is a better option than JSONP http://stackoverflow.com/a/7174902/2333214 – T J Jun 28 '16 at 05:38