如何将数据从ajax发送到spring控制器

时间:2016-09-23 10:43:20

标签: javascript java ajax spring model-view-controller

var TableDatatablesEditable = function () {

    var handleTable = function () {

        function restoreRow(oTable, nRow) {
            var aData = oTable.fnGetData(nRow);
            var jqTds = $('>td', nRow);

            for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
                oTable.fnUpdate(aData[i], nRow, i, false);
            }

            oTable.fnDraw();
        }

        function editRow(oTable, nRow) {
            var aData = oTable.fnGetData(nRow);
            var jqTds = $('>td', nRow);
            jqTds[0].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[0] + '">';
            jqTds[1].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[1] + '">';
            jqTds[2].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[2] + '">';
            jqTds[3].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[3] + '">';
            jqTds[4].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[4] + '">';
            jqTds[5].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[5] + '">';
            jqTds[6].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[6] + '">';
            jqTds[7].innerHTML = '<a class="edit" href="">Save</a>';
            jqTds[8].innerHTML = '<a class="cancel" href="">Cancel</a>';
            oTable.fnDraw();
        }

        function saveRow(oTable, nRow) {
            var jqInputs = $('input', nRow);
            oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
            oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
            oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
            oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
            oTable.fnUpdate(jqInputs[4].value, nRow, 4, false);
            oTable.fnUpdate(jqInputs[5].value, nRow, 5, false);
            oTable.fnUpdate(jqInputs[6].value, nRow, 6, false);
            oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 7, false);
            // oTable.fnUpdate('<a class="delete" href="">Delete</a>', nRow, 7, false);
            oTable.fnDraw();

            // console.log(globalSourceItem);
            //ajax call to sync data
            // var kbe = $this.closest('.source-item').find('.source-kbe').html();
            // var no_error = 1;
            // var kbe = $("#KBEid").prop("checked") ? 'Y': 'N';
            // var dgrp = $("#dgroupid").prop("checked") ? 'Y': 'N';
            // var dkey = $("#dupkeyid").prop("checked") ? 'Y': 'N';
            // var targeturl = $("#targeturl").val();

            var form_data = {
                itemid: globalSourceItem.substr(globalSourceItem.indexOf("-") + 1),
                columnName: jqInputs[0].value,
                displayName: jqInputs[1].value,
                format: jqInputs[2].value,
                KBE: jqInputs[3].value,
                dgroup: jqInputs[4].value,
                dupkey: jqInputs[5].value ,
                measurement: jqInputs[6].value ,
                times: new Date().getTime()
            };
            // console.log(form_data);
            // console.log($("#tourl").html());
            $.ajax({
                //url: $("#tourl").html(),
                url: 'save',
                type: 'POST',
                datatype: 'json',
                data: form_data,
                success: function(message) {
                    var j_obj = $.parseJSON(message);
                    // console.log(j_obj);return false;
                    if (j_obj.hasOwnProperty('success')) {
                        toastr.info('Item updated successfully');
                        setTimeout(function(){
                            window.location.reload();
                        },1000); 
                    } else {
                        toastr.info('There was a problem.');
                    }
                },
                error: function(xhr, textStatus, errorThrown) 
                {
                    alert("There seems to be a network problem. Please try again in some time.");
                    toastr.info('There seems to be a network problem. Please try again  some time.');
                }
            });

        }

        function cancelEditRow(oTable, nRow) {
            var jqInputs = $('input', nRow);
            oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
            oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
            oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
            oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
            oTable.fnUpdate(jqInputs[4].value, nRow, 4, false);
            oTable.fnUpdate(jqInputs[5].value, nRow, 5, false);
            oTable.fnUpdate(jqInputs[6].value, nRow, 6, false);
            oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 7, false);
            oTable.fnDraw();
        }

        var table = $('#sample_editable_1');

        var oTable = table.dataTable({

            // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
            // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js). 
            // So when dropdowns used the scrollable div should be removed. 
            //"dom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",

            "lengthMenu": [
                [5, 15, 20, -1],
                [5, 15, 20, "All"] // change per page values here
            ],

            // Or you can use remote translation file
            //"language": {
            //   url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json'
            //},

            // set the initial value
            "pageLength": 10,

            "scrollX": true,

            "language": {
                "lengthMenu": " _MENU_ records"
            },
            "columnDefs": [{ // set default column settings
                'orderable': true,
                'targets': [0]
            }, {
                "searchable": true,
                "targets": [0]
            }],
            "order": [
                [0, "asc"]
            ] // set first column as a default sort by asc
        });

        var tableWrapper = $("#sample_editable_1_wrapper");

        var nEditing = null;
        var nNew = false;

        $('#sample_editable_1_new').click(function (e) {
            e.preventDefault();

            if (nNew && nEditing) {
                if (confirm("Previous row not saved. Do you want to save it ?")) {
                    saveRow(oTable, nEditing); // save
                    $(nEditing).find("td:first").html("Untitled");
                    nEditing = null;
                    nNew = false;

                } else {
                    oTable.fnDeleteRow(nEditing); // cancel
                    nEditing = null;
                    nNew = false;

                    return;
                }
            }

            var aiNew = oTable.fnAddData(['', '', '', '', '', '','']);
            var nRow = oTable.fnGetNodes(aiNew[0]);
            editRow(oTable, nRow);
            nEditing = nRow;
            nNew = true;
        });

        table.on('click', '.delete', function (e) {
            e.preventDefault();

            if (confirm("Are you sure to delete this row ?") == false) {
                return;
            }

            var nRow = $(this).parents('tr')[0];
            oTable.fnDeleteRow(nRow);
            alert("Deleted! Do not forget to do some ajax to sync with backend :)");
        });

        table.on('click', '.cancel', function (e) {
            e.preventDefault();
            if (nNew) {
                oTable.fnDeleteRow(nEditing);
                nEditing = null;
                nNew = false;
            } else {
                restoreRow(oTable, nEditing);
                nEditing = null;
            }
        });

        var globalSourceItem;

        table.on('click', '.edit', function (e) {
            e.preventDefault();

            /* Get the row as a parent of the link that was clicked on */
            var nRow = $(this).parents('tr')[0];

            if (nEditing !== null && nEditing != nRow) {
                console.log($(this).html());
                /* Currently editing - but not this row - restore the old before continuing to edit mode */
                restoreRow(oTable, nEditing);
                editRow(oTable, nRow);
                nEditing = nRow;
            } else if (nEditing == nRow && this.innerHTML == "Save") {
                /* Editing this row and want to save it */
                saveRow(oTable, nEditing);
                nEditing = null;
                // alert("Updated! Do not forget to do some ajax to sync with backend :)");
            } else {
                /* No edit in progress - let's start one */
                // console.log($(this).html());
                globalSourceItem = $(this).attr('id');
                editRow(oTable, nRow);
                nEditing = nRow;
            }
        });
    }

    return {

        //main function to initiate the module
        init: function () {
            handleTable();
        }

    };

}();

jQuery(document).ready(function() {
    TableDatatablesEditable.init();
});

这是JavaScript代码和AJAX代码:

我需要将来自AJAX代码的数据(我们在浏览器中编辑的表数据)发送到spring MVC控制器,请帮帮我..

@RequestMapping(value = "/save1", method = RequestMethod.GET)
public ModelAndView dataTemplateedit(HttpServletRequest req) {
    /*String name=req.getParameter("aData[4]");
    System.out.println("name:"+name);*/
    String displayName=req.getParameter("displayname");
    String columnName=req.getParameter("columnName");
    String format=req.getParameter("format");
    String KBE=req.getParameter("KBE");
    String dgroup=req.getParameter("dgroup");
    String dupkey=req.getParameter("measurement");
    System.out.println(dupkey);
    System.out.println(format);
    System.out.println("hello");
    ListDataDefinition ldd=new ListDataDefinition();
    ldd.setDisplayName(displayName);
    ldd.setColumnName(columnName);
    ldd.setFormat(format);
    ldd.setKBE(KBE);
    ldd.setDgroup(dgroup);
    ldd.setDupkey(dupkey);
    DataTemplatesave.save(ldd);

    return new ModelAndView("save1");
}

这是Java代码,请帮帮我

1 个答案:

答案 0 :(得分:0)

据我所知,您不需要为每个参数执行request.getParameter,如果您已经拥有一个与您的请求参数相同的属性名称的bean。

你可以直接写如下:

CTPlotArea plotArea = xssfChart.getCTChart().getPlotArea();
CTMarker ctMarker = CTMarker.Factory.newInstance();
ctMarker.setSymbol(CTMarkerStyle.Factory.newInstance());
for (CTLineSer ser : plotArea.getLineChartArray()[0].getSerArray()) {
    ser.setMarker(ctMarker);
}

看起来您正在自动装配DataTemplatesave以获取建议,请保留驼峰以获得更好的代码可维护性。

@RequestMapping(value = "/save1", method = RequestMethod.GET)
public ModelAndView dataTemplateedit(ListDataDefinition ldd) {
    DataTemplatesave.save(ldd);
}