数据表将字段值关联到按钮,而 ajax 填充表

Datatables associate field value to button while ajax fills table

本文关键字:ajax 填充 按钮 字段 关联 数据表      更新时间:2023-09-26

我正在使用带有AJAX调用的数据表来输入值。我有一个删除按钮,可以从数据库调用Web服务器中删除行的用户。我想将用户名字段关联到按钮,以便我可以在 REST 调用中使用此值。这是我的表:

userTable = $('#usersTable').DataTable({
    // disable order and search on column
    columnDefs : [ {
        targets : 1,
        orderable : false,
        searchable : false,
    }, {
        targets : 4,
        orderable : false,
        searchable : false,
    } ],
    // fix problem with responsive table
    "autoWidth" : false,
    "ajax" : "table",
    "columns" : [ {
        "data" : "username"
    }, {
        data : "enabled",
        render : function(data, type, row) {
            if (data) {
                return '<input data="' + row.username + '" type="checkbox" name="my-checkbox" checked>';
            } else {
                return '<input data="' + row.username + '" type="checkbox" name="my-checkbox">';
            }
        }
    }, {
        "data" : "role.role"
    }, {
        "data" : "clientVersion.name",
        "defaultContent" : ""// this set empty string if clientVersion.name is null, otherwise datatables shows popup message with error
    }, {
        data : null,
        className : "center",
        defaultContent : '<button type="button" class="btn btn-danger" id="deleteUser" data-toggle="modal" data-href=data="' + row.username + '" data-target="#deleteUserModal">Delete</button>'
    } ],
    "fnDrawCallback" : function() {
        // Initialize checkbos for enable/disable user
        $("[name='my-checkbox']").bootstrapSwitch({
            size : "small",
            onColor : "success",
            offColor : "danger"
        });
        // $('#toggleChecked').bootstrapSwitch({size: "small", onColor:"success", offColor:"danger"});
    }
});

row.username那里不可用,是否有一种方法可以在按钮标签内设置用户名值?因此,我可以使用此代码通过模态传递值:

//Confirm delete user modal
$('#deleteUserModal').on('show.bs.modal', function (e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    $('#deleteUserHiddenId').val($(this).find('.btn-ok').attr('href'));
});

并致电:

$("#deleteUserModal").click(function(e) {
    e.preventDefault();
    var id= $('#deleteUserHiddenId').val();
});

我用了这个

$('#usersTable tbody').on( 'click', 'button', function () {
        usernameSelected = (userTable.row( $(this).parents('tr') ).data().username);
    } );

其中usernameSelected是一个JavaScript变量,我将其用作路径变量