
本文旨在解决如何使用 jQuery 和 DataTables 插件,将表单选择的值传递到后端 PHP 脚本,作为 SQL 查询的 WHERE 子句,从而动态更新 DataTables 表格。我们将重点介绍如何通过 AJAX 提交表单数据,并在 DataTables 中重新加载数据,以实现数据的动态筛选和展示。
首先,我们需要一个包含 zuojiankuohaophpcnselect> 元素的 HTML 表单,用于让用户选择过滤条件。同时,创建一个用于展示数据的 DataTables 表格。
<form method="POST" id="frm">
<select name="selectplace">
<option value="PLACE 1">PLACE 1</option>
<option value="PLACE 2">PLACE 2</option>
<option value="PLACE 3">PLACE 3</option>
</select>
<button type="submit" name="submitPlace">SUBMIT</button>
</form>
<div class="table-responsive">
<table class="table table-bordered table-striped text-center" id="place-table">
<thead>
<tr>
<th>PLACE #</th>
<th>PLACE NAME</th>
<th>TOTAL VISITORS</th>
</tr>
</thead>
<tfoot>
<tr>
<th>PLACE #</th>
<th>PLACE NAME</th>
<th>TOTAL VISITORS</th>
</tr>
</tfoot>
</table>
</div>接下来,使用 jQuery 初始化 DataTables,并配置 AJAX 数据源。
$(document).ready(function() {
var table = $('#place-table').DataTable({
"ajax": {
url: "json.php",
"dataSrc": "",
"data": function(d) {
var frm_data = $('#frm').serialize(); // 使用 serialize() 方法
return frm_data; // 直接返回序列化后的字符串
}
},
columns: [{
data: 'place_id',
}, {
data: 'place_name',
}, {
data: 'total_visitor',
}]
});
// 监听表单提交事件
$("#frm").submit(function(e) {
e.preventDefault(); // 阻止默认的表单提交行为
table.ajax.reload(); // 重新加载 DataTables 数据
});
});代码解释:
在 json.php 文件中,接收来自前端的表单数据,构建 SQL 查询,并返回 JSON 格式的数据。
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$selectedplace = $_POST['selectplace']; // 获取 selectplace 的值
// 安全起见,使用预处理语句防止 SQL 注入
$sql = "SELECT * FROM placestable WHERE place_name = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $selectedplace); // "s" 表示字符串类型
$stmt->execute();
$result = $stmt->get_result();
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = array(
"place_id"=>$row['id'],
"place_name"=> $row['place_name'],
"total_visitor"=> $row['total_visitor'],
);
}
echo json_encode($data);
$stmt->close();
$conn->close();
?>代码解释:
通过以上步骤,你可以实现将表单数据传递到后端,动态更新 DataTables 表格的功能。 记住,安全性是第一位的,务必采取措施防止 SQL 注入攻击。
以上就是使用 jQuery 和 DataTables 传递表单数据到数据库并动态更新表格的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号