执行Ajax请求时返回null值的技术问题咨询
解决Ajax请求返回null无法获取curent_day变量的问题
看起来你在通过Ajax向Yii2后端传递日期参数时,遇到了返回值为null的问题,我来帮你一步步排查和解决:
第一步:先确认前端是否正确获取并传递了参数
首先要排查的是前端的$('.owl-item.center .slide_day').text()是否真的拿到了预期的文本内容。很多时候文本可能包含空格、换行或者元素选择器不正确导致拿到空值。可以在Ajax请求前加调试代码:
// 先获取并处理文本,去掉前后空格 const targetDay = $('.owl-item.center .slide_day').text().trim(); console.log('准备传递的日期:', targetDay); // 打开浏览器控制台查看输出 $.ajax({ url: 'planing/next-day', data: {new_curent_day: targetDay}, dataType: 'json', type: 'POST', success: function(curent_day) { alert(curent_day); }, error: function(xhr, status, error) { alert(xhr.responseText + '|\n' + status + '|\n' +error); } });
如果控制台输出是空的,那说明你的元素选择器有问题,需要检查.owl-item.center .slide_day这个选择器是否能正确选中目标元素。
第二步:检查后端是否正确接收到参数
前端参数没问题的话,接下来排查后端是否拿到了值。在Yii2的actionNextDay方法里添加日志或直接返回接收到的参数:
public function actionNextDay() { if (Yii::$app->request->isAjax){ // 先直接获取参数并返回,排除模型的影响 $receivedDay = Yii::$app->request->post('new_curent_day'); // 可以把值写入服务器日志,方便查看 error_log('接收到的new_curent_day参数:' . $receivedDay); // 直接返回这个参数测试 return Json::encode($receivedDay); } }
如果此时返回的还是null,大概率是CSRF令牌缺失导致的——Yii2默认会拦截没有CSRF令牌的POST请求,导致参数无法正常接收。
第三步:给Ajax请求添加CSRF令牌
在前端Ajax请求的data里加上CSRF令牌:
$.ajax({ url: 'planing/next-day', data: { new_curent_day: $('.owl-item.center .slide_day').text().trim(), _csrf: $('meta[name="csrf-token"]').attr('content') // 新增CSRF令牌 }, dataType: 'json', type: 'POST', success: function(curent_day) { alert(curent_day); }, error: function(xhr, status, error) { alert(xhr.responseText + '|\n' + status + '|\n' +error); } });
同时要确保你的页面头部已经包含了CSRF元标签(Yii2的默认布局一般会自动生成):
<meta name="csrf-token" content="<?= Yii::$app->request->csrfToken ?>">
第四步:排查模型赋值的问题
如果前面的步骤已经能让后端返回正确的receivedDay值,但赋值给planing_model后返回null,那就要检查模型的定义:
- 确认
planing_model的curent_day属性是public的,或者有对应的setter方法; - 如果是ActiveRecord模型,要确保数据库表中存在
curent_day字段,并且模型的属性和字段名一致; - 可以在赋值后打印模型属性值,确认是否赋值成功:
public function actionNextDay() { if (Yii::$app->request->isAjax){ $receivedDay = Yii::$app->request->post('new_curent_day'); $this->planing_model->curent_day = $receivedDay; error_log('模型赋值后的curent_day:' . $this->planing_model->curent_day); return Json::encode($this->planing_model->curent_day); } }
按照这个顺序排查,应该能很快定位到问题所在~
内容的提问来源于stack exchange,提问作者markdeitchell
相关产品推荐
相关产品推荐

