You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Spring MVC为jQuery DataTables配置编辑删除按钮及跳转

Solution for Adding Dynamic Edit/Delete Buttons to jQuery DataTables

Got it, let's tackle this step by step. You've already got DataTables loading data via JSON, so we just need to make those buttons dynamic and wire up the delete functionality properly.

1. Fix Dynamic Edit Button URL

Right now your edit link uses a hardcoded 1 for the article ID. Instead, use DataTables' render function to generate the URL based on the row's actual idArticle value. Replace your static defaultContent for the actions column with this render callback:

Updated JS Column Configuration

columns: [
    { data: 'codeArt' },
    { data: 'rubrique.designation' },
    { data: 'fournisseur.nomFournisseur' },
    { data: 'refArt' },
    { data: 'designationC' },
    { data: 'quantite' },
    {
        render: function(data, type, row) {
            // Generate edit link with dynamic article ID
            const editBtn = `<a href="/article/modifier/${row.idArticle}" class="btn btn-xs btn-success" role="button">
                                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
                            </a>`;
            
            // Generate delete button with data-id attribute for later use
            const deleteBtn = `<a href="javascript:void(0);" class="btn btn-xs btn-danger delete-article-btn" role="button" data-id="${row.idArticle}">
                                <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
                            </a>`;
            
            // Add your view button back if needed, using row data for any dynamic parts
            const viewBtn = `<a class="btn btn-xs btn-default" href="#" role="button">
                                <span class="glyphicon glyphicon-file" aria-hidden="true"></span>
                            </a>`;
            
            return `${viewBtn} ${editBtn} ${deleteBtn}`;
        }
    }
]

This uses the row object (which contains your full Article data) to inject the correct idArticle into the edit link.

2. Wire Up Delete Functionality with AJAX

Your current delete button tries to target a modal with a dynamic ID that won't exist (since the table is populated via JSON). Instead, create a reusable modal and handle the delete via AJAX:

Step 2.1: Add a Reusable Delete Modal

Add this HTML somewhere in your page (before the table works well):

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteArticleModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="deleteModalLabel">Confirm Delete</h4>
            </div>
            <div class="modal-body">
                Are you sure you want to delete this article?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Delete</button>
            </div>
        </div>
    </div>
</div>

Step 2.2: Add Delete Button Click Handler

Add this JS right after your DataTables initialization:

// Store the ID of the article we want to delete
let articleIdToDelete;

// Open modal when delete button is clicked
$('#articleListTable').on('click', '.delete-article-btn', function() {
    articleIdToDelete = $(this).data('id');
    $('#deleteArticleModal').modal('show');
});

// Handle confirmation of delete
$('#confirmDeleteBtn').click(function() {
    $.ajax({
        url: `/article/supprimer/${articleIdToDelete}`,
        method: 'POST', // Use POST instead of GET for delete actions (better security practice)
        success: function() {
            // Close modal and refresh the table to reflect changes
            $('#deleteArticleModal').modal('hide');
            $('#articleListTable').DataTable().ajax.reload();
        },
        error: function() {
            alert('Failed to delete article. Please try again.');
            $('#deleteArticleModal').modal('hide');
        }
    });
});

Your current delete endpoint returns a redirect, which works for regular links but not AJAX calls. Update it to return a simple success/error response:

Updated Controller Delete Method

@RequestMapping(value = "/supprimer/{idArticle}", method = RequestMethod.POST)
@ResponseBody
public String deleteArticle(@PathVariable Long idArticle) {
    if (idArticle != null) {
        Article article = articleService.getById(idArticle);
        if (article != null) {
            // Add any pre-deletion validation checks here if needed
            articleService.remove(idArticle);
            return "success";
        }
    }
    return "error";
}

Quick Checks

  • Ensure your Article entity has an idArticle field (since we're referencing row.idArticle in the JS).
  • If your view button needs dynamic data (like a link to a detail page), use the same row object pattern as the edit button.

内容的提问来源于stack exchange,提问作者Nassim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:44:37