You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中使用AJAX标记通知已读时未传值的问题排查

问题排查与修复方案

你的代码存在多处问题,导致AJAX无法正常传递值并完成更新操作,逐一解决如下:

1. AJAX数据语法错误

JS代码中data对象的_token字段末尾缺少逗号,直接造成JSON格式报错,浏览器无法发送合法请求:

data: {
    "_token": "{{ csrf_token() }}", // 必须添加这个逗号
    "read": '1',
}

2. 未阻止a标签默认跳转行为

点击<a>标签会触发默认页面跳转,AJAX请求还未完成就被中断,根本无法抵达后端。需要在点击事件中阻止默认行为:

$('#readnotif').on('click', function(e) {
    e.preventDefault(); // 阻止a标签跳转
    // 后续AJAX代码保持不变
});

3. 路由与控制器参数不匹配

你的路由/readnotif未定义{id}参数,但控制器方法readnotif却要求接收$id,直接导致请求参数缺失报错。先修改路由添加id参数:

Route::post('/readnotif/{id}', 'readnotif')->name('task.read');

然后给a标签添加存储通知ID的属性,方便前端获取:

<a class="dropdown-item d-flex align-items-center" href="{{ route('task.edit', Crypt::encrypt($dokumentasi->id)) }}" id="readnotif" data-id="{{ $dokumentasi->id }}"></a>

最后在AJAX中拼接带ID的请求地址:

url: "{{ route('task.read', ':id') }}".replace(':id', $(this).data('id')),

4. 控制器逻辑错误

  • 参数顺序错误:Request实例必须放在参数列表前面,Laravel才能正确注入;
  • 冗余查询:已经使用Dokumentasi $dokumentasi隐式模型绑定,无需再用where('id', $id)查询;
  • 硬写参数:没有使用前端传递的read值,而是固定写死为1,失去了AJAX传参的意义。

修正后的控制器方法:

public function readnotif(Request $request, Dokumentasi $dokumentasi)
{
    $dokumentasi->update([
        "read" => $request->input('read', 1) // 优先取前端传值,默认设为1
    ]);
    return response()->json(['success' => true]); // 返回响应给前端
}

内容的提问来源于stack exchange,提问作者ProgrammerWannabe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 21:01:41