且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Ajax调用中删除DataTables中的行

更新时间:2023-12-04 11:35:28

也许已经太晚了,但无论如何我都会说。在网上搜索了两天之后,我找到了一个没有任何DataTable函数的简单解决方案

Maybe it's too late, but I will put it anyway. After two days of searching all over the web, I find a simple solution without any DataTable functions

<td>
 <button type="button" id="{{$lead->id}}"  name="{{$lead->id}}" onclick="deleteRecord(this.id,this)" data-token="{{ csrf_token() }}">Delete</button>
 </td>


上面这个单元格有一个onclick函数,它带有2个参数,第一个参数(这个.id)是按钮的id(来自DB,将传递给ajax以更新DB),第二个(this)是按钮本身的索引(稍后我们将提取索引)从它开始的行)

this cell above has an onclick function that takes 2 parameters, the first one (this.id) is the id of the button (that comes from the DB, and will be passed to ajax to update the DB), and the second one (this) which is the index of the button itself (later we will extract the index of the row from it)

function deleteRecord(mech_id,row_index) {
$.ajax({
        url:"{{action('MechanicController@destroy')}}",
        type: 'get',
        data: {
              "id": mech_id,
              "_token": token,
              },
        success: function ()
             {
              var i = row_index.parentNode.parentNode.rowIndex;
              document.getElementById("table1").deleteRow(i);
            }
     });  
}

现在在成功函数中,我使用了2行:
第一个是从按钮中提取行索引(2个父项,因为我们必须从按钮的父节点传递,在这种情况下,然后是行的父节点)

Now in the success function, I have used 2 lines: the first one is to extract the row index from the button (2 parents because we have to pass from the parent of the button, in this case , and then the parent of the which is the row)

第二行是table1的索引的简单删除行,这是我的表的名称

the second line is a simple delete row of our index from table1 which is the name of my table