我在加载包含多层嵌套的 JSON 时遇到问题。我有一个模型(位置),其中有一组与每个模型相关联的模型(项目)。
商品型号
Ext.define('SenchaSandbox.model.Item', {
extend: 'Ext.data.Model',
requires: ['Ext.data.Field'],
config: {
fields: ['id', 'name']
}
});
位置模型
Ext.define('SenchaSandbox.model.Location', {
extend: 'Ext.data.Model',
requires: ['Ext.data.Field', 'Ext.data.association.HasMany'],
uses: ['SenchaSandbox.model.Item'],
config: {
fields: ['id', 'name'],
associations: [{
type: 'hasMany',
model: 'SenchaSandbox.model.Item',
autoLoad: true,
name: 'items'
}]
}
});
位置存储
Ext.define('SenchaSandbox.store.LocationStore', {
extend: 'Ext.data.Store',
requires: [
'Location',
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json'
],
config: {
model: 'SenchaSandbox.model.Location',
storeId: 'LocationStore',
proxy: {
type: 'ajax',
url: 'DummyGood.json',
reader: {
type: 'json',
rootProperty: 'location'
}
}
}
});
在理想情况下,如果来自服务器的 JSON 如下所示,Sencha 将自动加载位置及其关联的项目。
良好的 JSON
{"location": [
{
"id": 100,
"name": "Location 1",
"items": [
{
"id": 1,
"name": "Item A"
},
{
"id": 2,
"name": "Item B"
}
]
},
{
"id": 200,
"name": "Location 2",
"items": [
{
"id": 3,
"name": "Item A"
},
{
"id": 4,
"name": "Item C"
}
]
}
]}
但是,服务器实际上返回 JSON,并带有一些额外的嵌套,如下所示。
错误(服务器)JSON
{"CollectionLocation": {
"collection": [
{
"id": 100,
"name": "Location 1",
"items": {
"collection": [
{
"id": 1,
"name": "Item A"
},
{
"id": 2,
"name": "Item B"
}
]
}
},
{
"id": 200,
"name": "Location 2",
"items": {
"collection": [
{
"id": 3,
"name": "Item A"
},
{
"id": 4,
"name": "Item C"
}
]
}
}
]
}}
假设我无法控制生成此 JSON 的服务器代码,那么我可以选择哪些选项来以干净的方式加载此数据?我仍然可以利用 Sencha 的自动加载功能,还是需要自己编写代码来创建子存储并用子模型填充它?
我在这里创建了一个 fiddle https://fiddle.sencha.com/#fiddle/7n6以防万一有人有时间弄乱示例。
最佳答案
使用Ext.data.TreeStore
而不是Ext.data.Store
http://docs-origin.sencha.com/touch/2.3.1/#!/api/Ext.data.TreeStore
关于javascript - 在 Sencha Touch 中自动加载多层嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24763415/