Ваша проблема имеет относительно простое решение.Я лично использую плагин jQuery для таблиц под названием DataTables found here
.Что касается вашего основного вопроса "Как удалить строку данных в таблице?"Это относительно просто.Поэтому вместо использования цикла for для итерации данных вы можете использовать jQuery .each
, что тоже довольно просто.Я собираюсь показать вам этот метод здесь, и я могу добавить больше к моему ответу позже, если вы хотите увидеть версию DataTables.
# please note that I use ES6 syntax in JS.
# this: function() {...code here...}
# is the same as this: (()=> {...code here...});
# ES6 allows for shorthand annonymous functions
// wait for document to load
$(document).ready(()=> {
// declare variable
let foo = "hello world";
// fetch data from the back end
$.get("data.php?foo=" + encodeURIComponent(foo), (data)=> {
# the $.get is the exact same as the AJAX code you used above but shorthanded
// the 'data' is a parameter in the annonymous function that is storing the data from the back end
console.log(data); // test that we are getting the data properly
// remove table rows if they exist
$("#mytable tbody").remove();
$("#mytable").each(data, (i, item)=> {
// add your data to the table by appending to the table
# You would just continue this until you have all the cells you need filled. I'm going to skip to the end with adding the btn now
$("#mytable").append('<tbody><tr><td>'+item.booking_email+'</td><td>'+item.booking_number+'</td><td><button class="btn btn-lg btn-danger deletebtn" id="'+item.booking_number+'">Delete</button></td></tbody>');
/* the button has to have a unique ID to be called on so I assigned it the booking numbers to the ID.
Here's how we would call on it*/
$(".deletebtn").unbind().click((d)=> {
// you must unbind it first or you will have multiple events fire and you only want a single event to fire
// pass the annonymous function a parameter (can be anything really I use d for delete)
console.log(d.target.id); // check to make sure the button is getting an ID.
// post to back end to delete then when it succeeds, we delete that row.
$.post("data.php", {deletefoo: d.target.id}, (data)=> {
// delete row by calling on the target and removing the parent in this case being the row 'tr'
$(d.target).parents('tr').remove();
});
});
});
$("#mytable").show();
});
});
Надеюсь, это поможет вашей проблеме.Дайте мне знать, если это помогает / работает для вас или нет.