检索handsontable数据Struts2的行动通过JSON不工作行动、数据、工作、handsontable

2023-09-10 16:07:55 作者:陪衬.

我使用Struts2的JSON的插件生成JSON数据和Ajax从JSON根据填充表(handsontable)数据(源)。

I am using struts2-json plugin to generate JSON data and Ajax to populate table (handsontable) with data from that JSON (according to the source).

现在,我需要检索使用Ajax通过JSON数据表Struts2的行动。 首先我实现填充表从Struts2的行动Handsontable经过JSON数据,这是很容易和它的作品。但是,为什么保存不工作,你可以在下面所附code看?

Now, I need to retrieve data from table to Struts2 Action using Ajax by JSON. First I've implemented populating table with data passed by JSON from Struts2 Action to Handsontable, that was quite easy and it works. But why save do not work as you can see in attached code below?

我在一个萤火虫的POST发送和调试要求看到的是检索在我JSONSaveAction行动,但该领域的数据不被填充JSON数据,为什么?数据不应被Struts2的JSON的插件自动绑定到Java对象?我究竟做错了什么?

As I see in a firebug the POST is sent and in debug the request is retrieved in my JSONSaveAction action but the field data is not being populated with JSON data, why? Data shouldn't be binded to java object automatically by struts2-json plugin? What am I doing wrong?

在handsontable部分功能 handsontable.getData()负责从表中获取整个数据。所以我使用它像这一点,但没有成功:

In handsontable part the function handsontable.getData() is responsible for getting whole data from table. So I am using it like this but without success:

$.ajax({
        url: "../json/saveJSONDataAction.action",
        data: {data: handsontable.getData()}, //returns all cells' data
        dataType: 'json',
        type: 'POST',
        success: function (res) {
            if (res.result === 'ok') {
                $console.text('Data saved');
            }
            else {
                $console.text('Save error');
            }
        }
    });

功能 handsontable.getData()真正找回了我检查了所有数据,而不是该数据不会绑定到java对象名单,其中,报告>数据在我JSONSaveAction行动。你知道为什么吗?

The function handsontable.getData() really retrieve all data what I checked but instead of that the data is not binded to java object List<Report> data in my JSONSaveAction action. Do you know why?

下面是截图与我的桌子和POST请求后萤火虫信息:

Here is screenshot with my table and firebug info after POST request:

@ParentPackage("json-default")
@Action(value="getJSONDataAction")
@Result(name="success", type="json")
public class JSONDataAction extends ActionSupport {
    private static final long serialVersionUID = 1L;

    private List<Report> data = new ArrayList<Report>();

    public JSONDataAction(){
        data.add(new Report(1, "Chris", true, "2008-01-01", "orange"));
        data.add(new Report(2, "Kate", false, "2013-03-03", "blue"));
        data.add(new Report(3, "Blade", true, "2013-05-03", "black"));
        data.add(new Report(4, "Zack", false, "2013-01-01", "yellow"));
    }

    public String execute() {
        return SUCCESS;
    }

    public List<Report> getData() {
        return data;
    }

    public void setData(List<Report> data) {
        this.data = data;
    }
}

JSON被发送到填充表自动生成的:

{"data":[
    {"active":true,"color":"orange","date":"2008-01-01","id":1,"name":"Chris"},
    {"active":false,"color":"blue","date":"2013-03-03","id":2,"name":"Kate"},
    {"active":true,"color":"black","date":"2013-05-03","id":3,"name":"Blade"},
    {"active":false,"color":"yellow","date":"2013-01-01","id":4,"name":"Zack"}]
}

行动通过JSON(不工作)检索从表中的数据:

下面的字段名单,其中,报告&GT;总是空,不填充数据与数据JSON:(

Action retrieving data from table via JSON (not working):

Here the field List<Report> data is always null, is not populated with data from JSON :(

@ParentPackage("json-default")
@Action(value="saveJSONDataAction")
@Result(name="success", type="json")
public class JSONSaveAction extends ActionSupport {
    private static final long serialVersionUID = 1L;

    private List<Report> data;

    public JSONSaveAction(){
    }

    public String execute() {
        try {
            JSONObject jsonData = (JSONObject) JSONSerializer.toJSON(data);
            String name = jsonData.getString("name");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    public List<Report> getData() {
        return data;
    }

    public void setData(List<Report> data) {
        this.data = data;
    }
}

报告类:

public class Report {
    private int id;
    private String name;
    private boolean active;
    private String date;
    private String color;

    //getters and setters
}

负载和放大器;保存数据和从表中通过JSON:

<div id="spreadsheet">
    <p>
        <button type="button" name="load">Load</button>
        <button type="button" name="save">Save</button>
    </p>
</div>
<div id="console" class="console"></div>

<script>
    var $container = $("#spreadsheet");
    var $console = $("#console");
    var $parent = $container.parent();
    $container.handsontable({
        startRows: 4,
        startCols: 20,
        rowHeaders: true,
        colHeaders: true,
        contextMenu: true,
        columns: [
            {data: "id", type: 'text'},
            {data: "name", type: 'text'},
            {data: "active", type: 'checkbox'},
            {data: "date", type: 'date'},
            {data: "color",
                type: 'autocomplete',
                source: ["yellow", "red", "orange", "green", "blue", "gray", "black", "white"]
            }
        ]
    });
    var handsontable = $container.data('handsontable');

    $parent.find('button[name=load]').click(function () {
        $.ajax({
            url: "../json/getJSONDataAction.action",
            dataType: 'json',
            type: 'GET',
            success: function (res) {
                handsontable.loadData(res.data);
                $console.text('Data loaded');
            }
        });
    });

    $parent.find('button[name=save]').click(function () {     
        $.ajax({
            url: "../json/saveJSONDataAction.action",
            data: {data: handsontable.getData()}, //returns all cells' data
            dataType: 'json',
            type: 'POST',
            success: function (res) {
                if (res.result === 'ok') {
                    $console.text('Data saved');
                }
                else {
                    $console.text('Save error');
                }
            },
            error: function () {
                $console.text('Save error.');
            }
        });
    });
</script>

请帮我如何正确地检索数据,从表到Java对象,因为它确实阻止了我。我不知道我做错了...

Please help me how to retrieve data from table to java object correctly, because it really blocked me. I do not know what I am doing wrong...

非常感谢您的任何输入!

Big thanks for any input!

推荐答案

我已经解决了。

1:在struts.xml中添加:

1: In struts.xml add:

<interceptor-ref name="json">
    <param name="enableSMD">true</param>
</interceptor-ref>

2:在Ajax请求地址:

2: In Ajax request add:

contentType: 'application/json'

3:更改JSON格式它会自动通过不良格式化handontable。有以JSON像一些字符:%5B%5D%7B%7D%,而不是22:[] {}

3: Change JSON format which is automatically bad formatted by handontable. There were in JSON some characters like: %5B %5D %7B %7D %22 instead of: [ ] { } "

我通过自己的fixedEn codeURI()函数取而代之

I've replaced them by own fixedEncodeURI() function:

var data = '{"data":' + fixedEncodeURI(JSON.stringify(handsontable.getData())) + '}';
$.ajax({
    url: "../json/saveJSONDataAction.action",
    data: data, //returns all cells' data
    dataType: 'json',
    contentType: 'application/json',
    type: 'POST',
    success: function (res) {
    }
  });

function fixedEncodeURI (str) {
    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%7B/g, '{').replace(/%7D/g, '}').replace(/%22/g, '"');
}