
在传统的 web 应用中,当用户需要根据某个条件筛选数据时,通常会通过提交表单来刷新整个页面。然而,这种方式会导致用户体验不佳。通过引入 ajax(asynchronous javascript and xml)技术,我们可以在不刷新页面的情况下,与服务器进行数据交互,实现数据的实时更新。
本教程将结合 CodeIgniter 的 MVC 架构和 jQuery 库,实现以下流程:
首先,我们需要在视图文件中准备好表格结构和下拉菜单。为了方便 JavaScript 操作,请为下拉菜单和表格的 zuojiankuohaophpcntbody> 元素添加唯一的 id 属性。同时,引入 jQuery 库。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>动态数据筛选</title>
<!-- 引入 jQuery 库 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
select {
padding: 5px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>数据实时筛选示例</h1>
<!-- 筛选下拉菜单 -->
<div class="filter-controls">
<label for="sourceFilter">按来源筛选:</label>
<select id="sourceFilter">
<option value="">所有来源</option>
<?php if (isset($sources) && $sources): ?>
<?php foreach ($sources as $source): ?>
<option value="<?php echo htmlspecialchars($source['title']); ?>">
<?php echo htmlspecialchars($source['title']); ?>
</option>
<?php endforeach; ?>
<?php endif; ?>
</select>
<!-- 如果有多个筛选条件,可以添加更多下拉菜单,并赋予不同的ID -->
<!-- <label for="categoryFilter">按分类筛选:</label>
<select id="categoryFilter">
<option value="">所有分类</option>
...
</select> -->
</div>
<!-- 数据表格 -->
<table id="recordsTable">
<thead>
<tr>
<th width="10%">来源</th>
<!-- 根据实际数据添加更多表头 -->
<!-- <th>其他字段</th> -->
</tr>
</thead>
<tbody id="recordsTableBody">
<?php
// 初始加载的数据
if (isset($records) && count($records) > 0) {
foreach ($records as $row) {
?>
<tr>
<td><?= htmlspecialchars($row->source); ?></td>
<!-- <td><?= htmlspecialchars($row->other_field); ?></td> -->
</tr>
<?php
}
} else {
echo '<tr><td colspan="1">暂无数据</td></tr>'; // 初始无数据时的提示
}
?>
</tbody>
</table>
<!-- JavaScript 逻辑 -->
<script>
$(document).ready(function() {
// 监听下拉菜单的 change 事件
$('#sourceFilter').on('change', function() {
var selectedSource = $(this).val(); // 获取当前选中的值
// 如果有多个筛选条件,可以这样收集所有值
// var filters = {
// source: $('#sourceFilter').val(),
// category: $('#categoryFilter').val() // 假设有另一个ID为 categoryFilter 的下拉菜单
// };
// 发送 AJAX 请求
$.ajax({
url: '<?php echo base_url('ajax_dropdown'); ?>', // CodeIgniter 的 base_url 辅助函数
type: 'GET',
data: {
source: selectedSource // 将筛选值作为 GET 参数发送
// 如果有多个筛选条件,可以发送 filters 对象
// data: filters
},
dataType: 'json', // 期望服务器返回 JSON 格式的数据
beforeSend: function() {
// 请求发送前显示加载提示
$('#recordsTableBody').html('<tr><td colspan="1">加载中...</td></tr>');
},
success: function(response) {
// AJAX 请求成功后处理数据
var records = response;
var html = '';
if (records && records.length > 0) {
// 遍历数据并构建表格行
$.each(records, function(index, record) {
html += '<tr>';
html += '<td>' + htmlspecialchars(record.source) + '</td>';
// 根据实际数据添加更多列
// html += '<td>' + htmlspecialchars(record.other_field) + '</td>';
html += '</tr>';
});
} else {
html = '<tr><td colspan="1">暂无数据</td></tr>';
}
// 更新表格的 tbody 内容
$('#recordsTableBody').html(html);
},
error: function(xhr, status, error) {
// AJAX 请求失败时处理错误
console.error("AJAX Error: ", status, error);
$('#recordsTableBody').html('<tr><td colspan="1">数据加载失败,请重试。</td></tr>');
}
});
});
// JavaScript 辅助函数,用于 HTML 转义,防止 XSS
function htmlspecialchars(str) {
if (typeof str !== 'string') {
return str; // 如果不是字符串,直接返回
}
var map = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'"
};
return str.replace(/[&<>"']/g, function(m) { return map[m]; });
}
});
</script>
</body>
</html>关键点:
在 CodeIgniter 的 application/config/routes.php 文件中,添加一条路由规则,将前端 AJAX 请求的 URL 映射到控制器的方法。
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
*/
// ... 其他路由规则 ...
// 为 AJAX 请求定义路由
$route['ajax_dropdown'] = 'your_controller/ajax_dropdown';说明:
创建一个控制器文件(例如 application/controllers/Your_controller.php),并在其中实现 ajax_dropdown 方法,用于接收前端请求、调用模型、并返回 JSON 数据。
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Your_controller extends CI_Controller {
public function __construct() {
parent::__construct();
// 载入模型,用于数据库操作
$this->load->model('your_model'); // 替换为你的模型名称
}
// 默认方法,用于加载初始视图和数据
public function index() {
// 假设这里获取初始的下拉菜单数据和表格数据
$data['sources'] = $this->your_model->get_all_sources();
$data['records'] = $this->your_model->get_all_records(); // 获取所有记录或默认记录
$this->load->view('your_view', $data); // 替换为你的视图文件
}
// 处理 AJAX 请求的方法
public function ajax_dropdown() {
// 确保请求是 AJAX 请求 (可选,但推荐)
if (!$this->input->is_ajax_request()) {
show_404(); // 如果不是 AJAX 请求,返回 404
}
// 获取前端发送的筛选参数
// $this->input->get() 方法用于获取 GET 请求参数
// TRUE 参数用于开启 XSS 过滤,提高安全性
$source_filter = $this->input->get('source', TRUE);
// 如果有多个筛选条件,可以这样获取
// $category_filter = $this->input->get('category', TRUE);
// $filters = ['source' => $source_filter, 'category' => $category_filter];
// 调用模型方法,根据筛选条件获取数据
$filtered_data = $this->your_model->get_filtered_records($source_filter); // 将筛选参数传递给模型
// 设置响应头为 JSON 格式
$this->output
->set_content_type('application/json')
->set_output(json_encode($filtered_data)); // 将数据编码为 JSON 并输出
}
}关键点:
创建一个模型文件(例如 application/models/Your_model.php),用于封装所有的数据库操作。
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Your_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->database(); // 载入数据库库
}
/**
* 获取所有用于下拉菜单的来源数据
* @return array
*/
public function get_all_sources() {
// 假设你的数据表中有一个 'title' 字段表示来源名称
$this->db->select('DISTINCT(title) as title');
$this->db->from('your_table_name'); // 替换为你的数据表名
$query = $this->db->get();
return $query->result_array(); // 返回数组,方便在视图中 foreach
}
/**
* 获取所有记录 (用于初始加载)
* @return array
*/
public function get_all_records() {
$query = $this->db->get('your_table_name'); // 替换为你的数据表名
return $query->result(); // 返回对象数组
}
/**
* 根据筛选条件获取记录
* @param string|null $source_filter 来源筛选值
* @return array
*/
public function get_filtered_records($source_filter = null) {
$this->db->select('source'); // 选择你需要展示的字段
// 如果有其他字段,可以添加:$this->db->select('以上就是基于 CodeIgniter 和 AJAX 实现动态下拉菜单筛选表格数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号