Search code examples
javascriptjqueryajaxbackbone.js

Ajax issue when loading json-file


I am saving a json string to local storage with setItem and get it back with getItem. This works, but when loading the same json string via ajax the object is becoming different.

Here is the original object in google-chrome browserconsole:

collection_parameter: Object
->OFFLINE: Array s
  ->_byId: Object
  ->models: Array[500]
..

Here is the stringified json (getItem, setItem) local-storage:

   {"OFFLINE":[{ "data_type":"OFFLINE",
                 "Number":"1",
                 "val_param_1_2_3":0 }, 
               {..},
               {..} ]
   }

When I am saving the above json-string in a file e.g. called Test.json and load it via ajax the object is not the same anymore.

Here the ajax call:

  $.ajax({                                    //Laden
        url:      'Test.json',
        method:   'GET',
        dataType: 'json',
        success: function(recieved_json_parameters) {

            collections_parameter=recieved_json_parameters;


        }//end success
    });//end ajax

The new object collection_parameter in google-chrome is now:

collection_parameter: Object
->OFFLINE: Array [500]

The additional nodes are missing. What can I do to get the exact same object-type as above??


UPDATE1: This is how I create the original json:

var collections_parameter = { OFFLINE: Backbone.Collection.extend() }
collections_parameter.OFFLINE = new collections_parameter.OFFLINE(json);

Solution

  • In order to store a Backbone Collection, you should save the raw data the collection has, which you can get with toJSON(): (the returned value is an array of objects)

    collection.toJSON() /* store the object returned by this function */
    

    (In your case, I think the collection is collection_parameter.OFFLINE)

    After retrieving the JSON representing the data, create a new Backbone Collection initialized with it:

    collection = new MyCollection(json)
    

    where MyCollection is the subclass of Backbone.Collection you're using, or Backbone.Collection itself, and json is the object you retrieved.


    The reason for this is that you need to store the actual data represented by the Collection. The Collection object itself provides you functions for accessing and changing the underlying data, but it's not the data itself, and therefore it should not be serialized and stored. After retrieving the raw data, you create a new Collection that will provide you the various functions for accessing the data.