
本文详解 codeigniter 中 ajax 请求参数在 controller 中可正常获取、却无法传入 model 的常见原因,重点分析变量传递缺失、json 输出错误及 sql 构建隐患,并提供完整可运行的修复方案。
本文详解 codeigniter 中 ajax 请求参数在 controller 中可正常获取、却无法传入 model 的常见原因,重点分析变量传递缺失、json 输出错误及 sql 构建隐患,并提供完整可运行的修复方案。
在 CodeIgniter 实现“加载更多”(Load More)功能时,一个典型陷阱是:Ajax 提交的参数能在 Controller 中通过 $this->input->post() 正确读取,却在调用 Model 方法时“丢失”——导致数据库查询生成无效 SQL(如 id 并非出在 Model 逻辑本身,而是参数传递链或响应处理环节存在疏漏。以下为系统性排查与修复指南:
✅ 1. 确保 Controller 正确接收并透传参数
你的 Controller 代码中已正确获取 pid,但需验证其类型与有效性,并显式传入 Model(避免隐式作用域或未定义变量):
public function loadmore_news()
{
// 启用 CSRF 保护时务必传递 token(若启用)
$this->security->csrf_verify(); // 或在 AJAX data 中附加 csrf_token
$lastid = $this->input->post('pid', true); // 第二个参数 TRUE 启用 XSS 过滤(推荐)
// 关键调试:确认值存在且为整型
if (empty($lastid) || !is_numeric($lastid)) {
header('Content-Type: application/json');
echo json_encode(['error' => 'Invalid or missing pid']);
return;
}
// 显式转换为整数,防止字符串参与 WHERE 比较
$lastid = (int) $lastid;
$more_news = $this->news_model->get_more_news($lastid);
// 修复:使用标准 json_encode(原代码 jsone_encode 是拼写错误!)
header('Content-Type: application/json');
echo json_encode($more_news);
}
⚠️ 注意:原文 jsone_encode() 是严重拼写错误,会导致 PHP 致命错误(函数未定义),使响应为空或报错,前端 res 可能为 null 或解析失败——这会间接掩盖 Model 参数问题。
✅ 2. Model 层健壮性增强(防御性编程)
Model 方法需主动校验输入,避免空值直接进入查询:
public function get_more_news($last_id)
{
// 强制校验:若 last_id 无效,返回空数组而非执行危险查询
if (empty($last_id) || !is_numeric($last_id)) {
log_message('error', 'Invalid $last_id passed to get_more_news: ' . print_r($last_id, true));
return [];
}
// 使用 Query Builder 安全构建条件(注意:where() 需传入完整条件数组或键值对)
$this->db->select('*')
->from('press')
->where('id where('domain_id', config_item('domain_id'))
->order_by('id', 'DESC')
->limit(6);
$query = $this->db->get();
// 调试:打印最终 SQL(开发环境启用)
// log_message('debug', 'SQL: ' . $this->db->last_query());
return $query->result();
}
? 提示:原 Model 中 where(array('id $last_id,...)) 的写法虽可工作,但 'id db->where('id
✅ 3. 前端 Ajax 增强与错误处理
修复 JavaScript 中潜在问题(如 URL 路径、CSRF Token、错误捕获):
function loadmore() {
var pid = $('#last_id').val();
var base_url = "<?php echo base_url(); ?>";
// 调试:确认 pid 有效
if (!pid || isNaN(pid)) {
console.error('Invalid pid:', pid);
return;
}
$.ajax({
type: "POST",
url: base_url + "News/loadmore_news",
data: {
'pid': pid,
'<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>' // 若启用 CSRF
},
dataType: 'json', // 明确声明期望 JSON 响应
success: function(res) {
if (res.error) {
console.error('Server error:', res.error);
return;
}
// 安全遍历:检查 res 是否为数组
if (Array.isArray(res)) {
res.forEach(function(item, i) {
// 渲染逻辑...
});
}
},
error: function(xhr, status, error) {
console.error('AJAX Error:', status, error, xhr.responseText);
}
});
}
? 核心总结
- 根本原因:jsone_encode() 拼写错误导致 Controller 响应中断,Model 虽被调用但结果未正确返回;同时 Model 缺乏输入校验,空 $last_id 直接生成非法 SQL。
-
关键修复点:
✅ 修正 json_encode() 拼写;
✅ Controller 中强制类型转换与空值校验;
✅ Model 使用显式 where() 避免条件构造歧义;
✅ 前端添加 dataType: 'json' 与完整错误处理。 - 最佳实践:所有外部输入(POST/GET)必须在进入业务逻辑前校验;Model 方法应具备“防呆”能力,拒绝非法参数并记录日志。
遵循以上步骤,即可彻底解决 Ajax 参数“止步于 Controller”的问题,确保数据流安全、稳定、可观测。











