项目链接:https://databasetable-net.000webhostapp.com/ https://databasetable-net.000webhostapp.com/
以下代码正确删除表中的一行:
$('#example').on('click', '.delete_btn', function () {
var row = $(this).closest('tr');
var data = table.row( row ).data().delete;
console.log(data);
alert("delete_btn clicked");
row.remove();
});
但是,它不会永久删除该行。如果刷新页面,被“删除”的行仍然存在。我相信这是因为我没有从数据库中删除该行。通常在 php 中,您可以安全地删除数据库中的一行,如下所示:
id = mysqli_real_escape_string($con, $_GET['del']);
$stmt = $con->prepare("DELETE FROM employees WHERE id = ? LIMIT 1");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
header('location: index.php');
编辑:修改后的代码 Index.php:
(document).ready(function() {
var asc = true;
var table = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "server.php",
"type": "POST",
},
//http://live.datatables.net/xijecupo/1/edit
columnDefs: [{
targets: -1,
defaultContent: '<button type="button" class="delete_btn">Delete</button>'
}],
rowGroup: {
dataSrc: 1
}
});
$(function(){
$(document).on('click','.delete_btn',function(){
var del_id= $(this).closest('tr');
var ele = $(this).parent().parent(); //removed the "$" from the ele variable. It's a js variable.
console.log(del_id);
$.ajax({
type:'POST',
url:'delete.php',
dataType: 'json', //This says I'm expecting a response that is json encoded.
data: { 'del_id' : del_id},
success: function(data){ //data is an json encoded array.
console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.
if(data['success']){ //You are checking for true/false not yes or no.
console.log('You successfully deleted the row.');
alert("delete btn clicked");
ele.remove();
}else{
console.log('The row was not deleted.');
}
}
});
});
}); //http://jsfiddle.net/zfohLL0a/
}); //end doc ready
删除.php代码:
$del_id = $_POST['del_id'];
$stmt = $conn->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();
$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
$array['success'] = TRUE;
}
echo json_encode($array);
?>
部分解决方案: 如何设置 ajax 的示例格式。 https://github.com/sokchab/phpserverside/blob/master/index.html您必须首先使用原始 server.php 的 datatables.net "ajax": 方法。但之后你对 add.php、delete.php 等使用普通的 $.ajax 方法。这很令人困惑,因为你对 ajax 使用了两种不同的语法。最简单的方法是查看示例链接。
讨论向 ajax/json 发送信息和从 ajax/json 发送信息的另一个有用的链接是one https://stackoverflow.com/questions/18062951/jquery-ajax-data-shows-object-object two http://api.jquery.com/jQuery.ajax/ three https://stackoverflow.com/questions/38617157/removing-rows-from-datatables-from-a-ajax-call?rq=1 Four https://stackoverflow.com/questions/19724383/delete-row-with-ajax-function-and-php