gpt4 book ai didi

json - ExtJS 5.1 不会向我的服务器发送嵌套的 JSON 对象

转载 作者:行者123 更新时间:2023-12-04 14:55:31 24 4
gpt4 key购买 nike

我正在尝试通过我商店的代理向我的服务器发送一个嵌套的 JSON 对象。我使用的是 ExtJS 5.1,在下面的代码中,我使用了 hasMany 属性来指定嵌套的 JSON 模型。

Ext.define('MyApp.model.PersonStore',{
extend: 'Ext.data.Store',
model: 'MyApp.model.Person',
storeId: 'PersonStore',
proxy: {
type: 'ajax',
url: 'http://localhost:80/index.php?person=create',
reader: {
type: 'json'
},
writer: {
type: 'json'
}
}
});

Ext.define('MyApp.model.Person',{
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'age', type: 'int'},
],
hasMany: {
model: 'MyApp.model.Item',
name: 'items',
associationKey: 'items'
}
});

Ext.define('MyApp.model.Item',{
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: 'int'
},
{
name: 'itemType',
type: 'string'
}
],
belongsTo: 'MyApp.model.Person'
});

然后在我的 Controller 中创建一个新的 Person 时,我这样做:

var store = grid.getStore();
store.add({name: 'Steve', age: '50'});
var lastInsertedPerson = store.last();
var items = lastInsertedPerson.items();
items.add({itemType: 'item1'});
items.add({itemType: 'item2'});

store.sync();

然后以这种格式发送 POST 请求:

{"id":"MyApp.model.Person-1", "name":"Steve", "age":"50"}

但我希望它是:

{"id":"MyApp.model.Person-1", "name":"Steve", "age":"50", "items":[{"itemType":"item1"}, {"itemType":"item2"}]}

那么为什么POST请求中的json对象不包含嵌套的Item对象呢?

最佳答案

为了使嵌套数据出现在 post 对象中,您必须在父模型的代理的 writer 对象中设置一个配置。因此,如果您将 Person 模型更改为看起来类似于嵌套对象下方的代码:

Ext.define('MyApp.model.Person',{
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'age', type: 'int'},
],
hasMany: {
model: 'MyApp.model.Item',
name: 'items',
associationKey: 'items'
},
proxy: {
url: '/url/to/your/backend/service',
writer: {
type: 'json',
allDataOptions: {
associated: true
}
}
}
});

请注意,编写器也有一个 partialDataOptions 配置,因此如果您希望嵌套数据在 PUT 中通过,则必须在那里设置 associated 配置以及。查看Ext Docs有关编写器配置选项的更多详细信息。

关于json - ExtJS 5.1 不会向我的服务器发送嵌套的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30050245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com