首先,添加自定義數據屬性的複選框
<input type="checkbox" data-id="'.$data['id'].'" data-status="'.$data['status'].'" ../>
在JavaScript,
// IIFE (Immediately Invoke Function Expressions)
(function (myapp){
myapp(window.jQuery, window, document);
}(function myapp($, window, document){
// $ is now locally scoped
$(function(){
// dom is now ready
var dtTable = $("#sometable").DataTable();
// dom events
$(document).on("change", '.btnedit', function(){
var $this = $(this);
var id = $this.attr("data-id");
var status = $this.attr("data-status");
// send ajax request
$.ajax({
url: 'path-to-your-php-file',
type: 'post',
dataType: 'json',
data: {
id: id,
status: status
},
beforeSend: function(){
// do something here before sending ajax
},
success: function (data){
// do something here
if(data.success){
// update your table, or any html dom you want here
// if you want to add/remove rows from your dataTable,
// you can refer here
// https://datatables.net/reference/api/row.add()
// https://datatables.net/reference/api/row().remove()
//
}
},
error: function (data){
// do something here if error
// console.warn(data);
}
});
});
});
// The rest of the code goes here
}));
在你的PHP文件,
<?php
$id = $_POST['id'];
$status = $_POST['status'];
// do your update codes here
//
// after successful update return something so in your ajax you
// will know what happened behind the scene
$response = array('success' => false, 'msg' => 'Some error message');
if(some_update_function_success()){
$response = array('success' => true, 'msg' => 'Some success message');
}
echo json_encode($response);
你能否提供一個工作代碼 –
PHP沒有複選框點擊。它是爲瀏覽器生成HTML的服務器端語言......一旦瀏覽器顯示頁面,就無法與PHP用於生成HTML的源代碼進行通信 - 它只是文本,畢竟沒有固有的功能。如果您想要將數據從瀏覽器發送到服務器,您需要調查諸如html表單或更高級的功能AJAX –