How to consume data created with jQuery AJAX in SlickGrid?

最后都变了- 提交于 2020-01-23 22:19:26

问题


Kinda stuck on this and just haven't been able to grok how to do it.

If I use a hard-coded array for data it works as expected, but if I issue a call to the endpoint the data is never bound to the grid, although I can see the json call being made through fiddler.

Thank you, Stephen

<script type="text/javascript">
    var grid;
    var data = [];

    var columns = [
                    { id: "#", name: "", width: 40, behavior: "selectAndMove", selectable: false, resizable: false, cssClass: "cell-reorder dnd" },
                    { id: "id", name: "id", field: "id", sortable: true },
                    { id: "FoodGroupId", name: "FoodGroupId", field: "FoodGroupId", editor: TextCellEditor, sortable: true },
                    { id: "Description", name: "Description", field: "Description", editor: TextCellEditor, sortable: true },
                    { id: "FdGrp_Cd", name: "FdGrp_Cd", field: "FdGrp_Cd", editor: TextCellEditor, sortable: true },
                    { id: "Long_Desc", name: "Long_Desc", field: "Long_Desc", editor: TextCellEditor, sortable: true },
                    { id: "Shrt_Desc", name: "Shrt_Desc", field: "Shrt_Desc", editor: TextCellEditor, sortable: true },
                    { id: "ComName", name: "ComName", field: "ComName", editor: TextCellEditor, sortable: true },
                    { id: "ManufacName", name: "ManufacName", field: "ManufacName", editor: TextCellEditor, sortable: true },
                    { id: "Survey", name: "Survey", field: "Survey", editor: TextCellEditor, sortable: true },
                    { id: "Ref_Desc", name: "Ref_Desc", field: "Ref_Desc", editor: TextCellEditor, sortable: true },
                    { id: "Refuse", name: "Refuse", field: "Refuse", editor: TextCellEditor, sortable: true },
                    { id: "SciName", name: "SciName", field: "SciName", editor: TextCellEditor, sortable: true },
                    { id: "N_Factor", name: "N_Factor", field: "N_Factor", editor: TextCellEditor, sortable: true },
                    { id: "Pro_Factor", name: "Pro_Factor", field: "Pro_Factor", editor: TextCellEditor, sortable: true },
                    { id: "Fat_Factor", name: "Fat_Factor", field: "Fat_Factor", editor: TextCellEditor, sortable: true }
                ];

    var options = {
        editable: true,
        enableAddRow: true,
        enableRowReordering: true,
        enableCellNavigation: true,
        forceFitColumns: true,
        autoEdit: false
    };

    function requiredFieldValidator(value) {
        if (value == null || value == undefined || !value.length)
            return { valid: false, msg: "This is a required field" };
        else
            return { valid: true, msg: null };
    }

    $(function () {

        data = $.getJSON("http://localhost/com.patten.root/RDA/GetDataAJAX");

        grid = new Slick.Grid("#myGrid", data, columns, options);

        grid.setSelectionModel(new Slick.RowSelectionModel());

        var moveRowsPlugin = new Slick.RowMoveManager();

        moveRowsPlugin.onBeforeMoveRows.subscribe(function (e, data) {
            for (var i = 0; i < data.rows.length; i++) {
                // no point in moving before or after itself
                if (data.rows[i] == data.insertBefore || data.rows[i] == data.insertBefore - 1) {
                    e.stopPropagation();
                    return false;
                }
            }

            return true;
        });

        moveRowsPlugin.onMoveRows.subscribe(function (e, args) {
            var extractedRows = [], left, right;
            var rows = args.rows;
            var insertBefore = args.insertBefore;
            left = data.slice(0, insertBefore);
            right = data.slice(insertBefore, data.length);

            for (var i = 0; i < rows.length; i++) {
                extractedRows.push(data[rows[i]]);
            }

            rows.sort().reverse();

            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                if (row < insertBefore)
                    left.splice(row, 1);
                else
                    right.splice(row - insertBefore, 1);
            }

            data = left.concat(extractedRows.concat(right));

            var selectedRows = [];
            for (var i = 0; i < rows.length; i++)
                selectedRows.push(left.length + i);

            grid.resetActiveCell();
            grid.setData(data);
            grid.setSelectedRows(selectedRows);
            grid.render();
        });

        grid.registerPlugin(moveRowsPlugin);

        grid.onDragInit.subscribe(function (e, dd) {
            // prevent the grid from cancelling drag'n'drop by default
            e.stopImmediatePropagation();
        });

        grid.onDragStart.subscribe(function (e, dd) {
            var cell = grid.getCellFromEvent(e);
            if (!cell)
                return;

            dd.row = cell.row;
            if (!data[dd.row])
                return;

            if (Slick.GlobalEditorLock.isActive())
                return;

            e.stopImmediatePropagation();
            dd.mode = "recycle";

            var selectedRows = grid.getSelectedRows();

            if (!selectedRows.length || $.inArray(dd.row, selectedRows) == -1) {
                selectedRows = [dd.row];
                grid.setSelectedRows(selectedRows);
            }

            dd.rows = selectedRows;
            dd.count = selectedRows.length;

            var proxy = $("<span></span>")
                    .css({
                        position: "absolute",
                        display: "inline-block",
                        padding: "4px 10px",
                        background: "#e0e0e0",
                        border: "1px solid gray",
                        "z-index": 99999,
                        "-moz-border-radius": "8px",
                        "-moz-box-shadow": "2px 2px 6px silver"
                    })
                    .text("Drag to Recycle Bin to delete " + dd.count + " selected row(s)")
                    .appendTo("body");

            dd.helper = proxy;

            $(dd.available).css("background", "pink");

            return proxy;
        });

        grid.onDrag.subscribe(function (e, dd) {
            if (dd.mode != "recycle") {
                return;
            }
            e.stopImmediatePropagation();
            dd.helper.css({ top: e.pageY + 5, left: e.pageX + 5 });
        });

        grid.onDragEnd.subscribe(function (e, dd) {
            if (dd.mode != "recycle") {
                return;
            }
            e.stopImmediatePropagation();
            dd.helper.remove();
            $(dd.available).css("background", "beige");
        });


        $("#dropzone")
                .bind("dropstart", function (e, dd) {
                    $(this).css("background", "yellow");
                })
                .bind("dropend", function (e, dd) {
                    $(dd.available).css("background", "pink");
                })
                .bind("drop", function (e, dd) {
                    var rowsToDelete = dd.rows.sort().reverse();
                    for (var i = 0; i < rowsToDelete.length; i++) {
                        data.splice(rowsToDelete[i], 1);
                    }
                    grid.invalidate();
                    grid.setSelectedRows([]);
                });


        grid.onAddNewRow.subscribe(function (e, args) {
            var item = { name: "New task", complete: false };
            $.extend(item, args.item);
            data.push(item);
            grid.invalidateRows([data.length - 1]);
            grid.updateRowCount();
            grid.render();
        });
    })
</script>

回答1:


That's not the way $.getJSON() works. The call is asynchronous. This means that the request is being fired and the code execution continues to the next line immediately. So when you get to this line:

grid = new Slick.Grid("#myGrid", data, columns, options);

the value of the data variable is not set.

To solve $.getJSON() provides a callback function after the response has returned. So you should initialise the grid in there. Something like this:

$.getJSON("http://localhost/com.patten.root/RDA/GetDataAJAX", function(data) {
  // data contains the response from the ajax call at this point
  grid = new Slick.Grid("#myGrid", data, columns, options);
});

For more info see here.



来源:https://stackoverflow.com/questions/8372857/how-to-consume-data-created-with-jquery-ajax-in-slickgrid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!