如何获取jqGrid拖拽排序后的新行顺序并构建序列数组?
Let's break this down into actionable steps to get your drag-sorted rows saved properly. First, we need to enhance jqGrid's sortable functionality to capture the new order, build the required data structure, and finally send it to your backend via AJAX.
Step 1: Enable Drag Sorting with Update Event
Your existing sortable: true enables dragging, but we need to hook into the update event that fires after a row is dropped into a new position. Replace your current sortable: true line with this expanded configuration:
sortable: { update: function(ev, ui) { // Logic to capture and save the new order goes here } },
Step 2: Build the Field ID to Seq Mapping
Inside the update event handler, we'll loop through all grid rows, grab each row's field_id, and assign its new sequential field_seq value (starting at 1). Here's how to construct that mapping:
update: function(ev, ui) { const $grid = $(this); const sortOrder = {}; // Loop through every visible row in the grid $grid.find('tr.jqgrow').each(function(index) { // Get the unique field_id for this row const fieldId = $grid.jqGrid('getRowData', $(this).attr('id')).field_id; // Assign sequence number (index + 1 since indexes start at 0) sortOrder[fieldId] = index + 1; }); // Now sortOrder contains the data you need: { "219110": 1, "219111": 2, ... } }
Step 3: Submit Data to Backend via AJAX
Next, retrieve the form_id from sessionStorage and send both it and the sortOrder mapping to your backend endpoint. Add this AJAX call right after building the sortOrder object:
// Fetch form_id from sessionStorage const formId = sessionStorage.getItem('form_id'); // Send the data to your backend $.ajax({ url: '/ajax/questions/update-sequence', // Replace with your actual backend endpoint type: 'POST', contentType: 'application/json', data: JSON.stringify({ form_id: formId, sequence: sortOrder }), success: function(response) { // Handle successful save (e.g., show a confirmation message) console.log('Row order saved successfully!', response); // Optional: Refresh the grid to reflect updated seq values $grid.trigger('reloadGrid'); }, error: function(xhr, status, error) { // Handle errors (e.g., notify the user of the failure) console.error('Failed to save row order:', error); // Optional: Revert to original sort order if save fails $grid.jqGrid('sortGrid', 'seq', true); } });
Full Updated jqGrid Configuration
Here's how your complete grid code will look with all changes integrated:
$(document).ready(function () { $("#thegrid").jqGrid({ url: "/ajax/questions/get/" + form_id, datatype: "json", colNames: ['id', 'grid_id', 'seq', 'type', 'text'], colModel: [ {name: 'field_id', index: 'id', width: 100, editable: false, search: false}, {name: 'grid_id', index: 'grid_id', width: 50, editable: false, search: false}, {name: 'field_seq', index: 'seq', width: 45, editable: false, search: false}, {name: 'type', index: 'type', width: 125, editable: false, search: false}, {name: 'field_name', index: 'text', width: 585, search: false} ], autowidth: true, rowNum: 200, cmTemplate: {width: 300, autoResizable: true}, iconSet: "fontAwesome", guiStyle: "bootstrap", autoResizing: {compact: true, resetWidthOrg: true}, viewrecords: true, autoencode: true, // Updated sortable with order save logic sortable: { update: function(ev, ui) { const $grid = $(this); const sortOrder = {}; $grid.find('tr.jqgrow').each(function(index) { const fieldId = $grid.jqGrid('getRowData', $(this).attr('id')).field_id; sortOrder[fieldId] = index + 1; }); const formId = sessionStorage.getItem('form_id'); $.ajax({ url: '/ajax/questions/update-sequence', type: 'POST', contentType: 'application/json', data: JSON.stringify({ form_id: formId, sequence: sortOrder }), success: function(response) { console.log('Row order saved successfully!', response); $grid.trigger('reloadGrid'); }, error: function(xhr, status, error) { console.error('Failed to save row order:', error); $grid.jqGrid('sortGrid', 'seq', true); } }); } }, pager: true, toppager: true, hoverrows: true, multiselect: true, multiPageSelection: false, rownumbers: true, loadonce: true, autoresizeOnLoad: true, forceClientSorting: true, ignoreCase: true, prmNames: {id: "field_id"}, jsonReader: {id: "field_id"}, localReader: {id: "field_id"}, navOptions: {edit: false, add: false, search: false, del: false, refresh: true}, pgbuttons: false, pginput: false, caption: "Questions", height: 100, editurl: '/ajax/questions/edit', onSelectRow: function () { // .... }, loadComplete: function () { // ... } }); });
Key Notes
- Ensure your backend endpoint is set up to accept a JSON payload with
form_idandsequence(the object mapping field IDs to their new sequence numbers). - The
reloadGridcall in the success handler refreshes the grid to show updatedfield_seqvalues (works withloadonce: trueby re-sorting local data). - The error handler includes a fallback to revert the grid to its original sequence, preventing user confusion if the save fails.
内容的提问来源于stack exchange,提问作者ReynierPM

