简体   繁体   English

如何更改ExtJS 4.2的.save()JSON输出

[英]How do I change the .save() JSON output for ExtJS 4.2

I have a problem save data to my database using an ExtJS updateable grid. 我有一个问题,使用ExtJS可更新网格将数据保存到我的数据库。 I'm working with a REST API that I have written in Progress ABL. 我正在使用我在Progress ABL中编写的REST API。 The API is working but the Input JSON and Output JSON is very specific. API正在运行,但输入JSON和输出JSON非常具体。

I can read the JSON data into my grid and display it, but when I want to save a new record the grid creates a wrong JSON output. 我可以将JSON数据读入我的网格并显示它,但是当我想保存新记录时,网格会创建一个错误的JSON输出。

My output has to be like this: 我的输出必须是这样的:

   {
      "request":
        {
          "dsUsers":
            {
              "ttUsers":
                [{"ID":20,"LOGIN":"test","PASS":"","ID_ADDR":0,"ID_CUST":0}]
            }
        }
    }

But I'm not able to create the request and dsUsers groups in the writer. 但是我无法在编写器中创建请求和dsUsers组。 I have tested a lot but I don't really know what I have to change to make it work. 我已经测试了很多,但我真的不知道我需要改变什么才能使它工作。

Thanks 谢谢

Base Ext.data.writer.Json allows you to define only root data property. Base Ext.data.writer.Json允许您仅定义根数据属性。 However if you need more custom structure like this, you can quite easily create your own writer. 但是,如果您需要更多这样的自定义结构,您可以非常轻松地创建自己的编写器。

Your writer should extend from Ext.data.writer.Json and override writeRecords method. 您的编写者应该从Ext.data.writer.Json扩展并覆盖writeRecords方法。 This method add records data into request. 此方法将记录数据添加到请求中。

In your case custom writer should look like this: 在您的情况下,自定义编写器应如下所示:

Ext.define('myWriter', {
    extend: 'Ext.data.writer.Json',
    writeRecords: function(request, data) {
        var root = this.root;        

        if (this.expandData) {
            data = this.getExpandedData(data);
        }

        if (this.allowSingle && data.length === 1) {
            // convert to single object format
            data = data[0];
        }

        request.jsonData = request.jsonData || {};
        request.jsonData['request'] = {
            'dsUsers': {}
        };

        request.jsonData['request']['dsUsers'][root] = data;

        return request;
    }    
});

Then you can use your custom writer in model or store proxy: 然后,您可以在模型或商店代理中使用自定义编写器:

Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name', 'email'],
    proxy: {
        type: 'rest',
        writer: Ext.create('myWriter', {
            root: 'ttUsers',
            mainRoot: 'dsUsers'
        }),
        url : '/users'
    }            
});

Of course you can create custom writer more configurable and reusable by defining name of "request" and "dsUsers" attributes in config. 当然,您可以通过在config中定义"request""dsUsers"属性的名称来创建更具可配置性和可重用性的自定义"dsUsers"

Fiddle with example: https://fiddle.sencha.com/#fiddle/33l 举例说明: https//fiddle.sencha.com/#fiddle/33l

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM