我正在使用setItem将json字符串保存到本地存储中,并使用getItem将其返回。这是可行的,但是当通过ajax加载相同的json字符串时,对象将变得不同。
这是google-chrome浏览器控制台中的原始对象:
collection_parameter: Object
->OFFLINE: Array s
->_byId: Object
->models: Array[500]
..
这是字符串化的json(getItem,setItem)本地存储:
{"OFFLINE":[{ "data_type":"OFFLINE",
"Number":"1",
"val_param_1_2_3":0 },
{..},
{..} ]
}
当我将上述json-string保存在名为Test.json的文件中并通过ajax加载时,对象不再相同。
这里是ajax调用:
$.ajax({ //Laden
url: 'Test.json',
method: 'GET',
dataType: 'json',
success: function(recieved_json_parameters) {
collections_parameter=recieved_json_parameters;
}//end success
});//end ajax
google-chrome中的新对象collection_parameter现在为:
collection_parameter: Object
->OFFLINE: Array [500]
其他节点丢失。我该怎么做才能获得与上述完全相同的对象类型?
UPDATE1:这就是我创建原始json的方式:
var collections_parameter = { OFFLINE: Backbone.Collection.extend() }
collections_parameter.OFFLINE = new collections_parameter.OFFLINE(json);
为了存储Backbone Collection
,您应该保存集合具有的原始数据,您可以通过以下方式获取该数据toJSON()
:(返回值是对象数组)
collection.toJSON() /* store the object returned by this function */
(对于您而言,我认为该集合是collection_parameter.OFFLINE
)
检索表示数据的JSON之后,创建一个Collection
用它初始化的新Backbone :
collection = new MyCollection(json)
其中MyCollection是Backbone.Collection
您正在使用的子类或其Backbone.Collection
本身,并且json
是您检索的对象。
这样做的原因是您需要存储由表示的实际数据Collection
。该Collection
对象本身为您提供功能访问和更改底层数据,但它不是数据本身,因此它不应该被序列化和存储。检索原始数据后,您将创建一个新文件Collection
,该文件将为您提供用于访问数据的各种功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句