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

如何使用Ajax success回调创建动态表格并解决$users未定义错误

问题核心原因

  • 你的Blade模板中@foreach ($users as $user)是服务端渲染逻辑,页面首次加载时如果渲染该视图的控制器没有传入$users变量,会直接抛出未定义错误。
  • 你当前的AJAX请求仅获取了JSON格式的用户数据,没有将数据插入到表格中,也没有更新模态框的DOM内容,直接弹出模态框自然不会展示动态数据。
  • 额外逻辑错误:控制器中使用firstOrFail()查询返回的是单个用户对象,不是集合,Blade中不需要写@foreach循环遍历。

方案一:前端动态渲染DOM(推荐,前后端分离逻辑更清晰)

1. 修改模态框内的表格代码

去掉服务端循环逻辑,预留动态渲染的容器:

<table id="employee">
  <tr>
    <th>ID Type</th>
    <th>ID Number</th>
  </tr>
  <tbody id="employee-tbody"></tbody>
</table>

2. 修改AJAX逻辑

拿到返回数据后手动渲染到表格中:

$(document).on('click', '.showdata', function(){
    var id = $(this).attr('id');
    $.ajax({
        url: "/search/"+id+"/searchInfo",
        dataType:"json",
        success:function(res){
            // 清空旧数据
            $('#employee-tbody').empty();
            // 插入单条用户数据
            const user = res.users;
            $('#employee-tbody').append(`
              <tr>
                <td>${user.id_type}</td>
                <td>${user.id_number}</td>
              </tr>
            `);
            $('#informationmodal').modal('show');
        }
    })
});

如果你需要查询多条用户数据,控制器中将firstOrFail()改为get(),返回的是用户集合,AJAX中循环res.users插入多条<tr>即可。

方案二:服务端返回渲染好的HTML片段(适合复杂表格场景)

1. 新建表格片段模板

新建resources/views/partials/employee-table.blade.php:

<table id="employee">
  <tr>
    <td>ID Type</td>
    <td>ID Number</td>
  </tr>
  <tr>
    <td>{{ $user->id_type }}</td>
    <td>{{ $user->id_number }}</td>
  </tr>
</table>

2. 修改控制器代码

直接返回渲染后的HTML片段:

public function searchInfo($id)
{
    if(request()->ajax())
    {
        $user = myModal::where('fk_emp_id','=', $id)->firstOrFail();
        return view('partials.employee-table', compact('user'))->render();
    }
}

3. 修改AJAX逻辑

接收HTML片段直接插入模态框:

$(document).on('click', '.showdata', function(){
    var id = $(this).attr('id');
    $.ajax({
        url: "/search/"+id+"/searchInfo",
        dataType:"html",
        success:function(html){
            // 将返回的表格插入模态框内容区,替换原有内容
            $('#informationmodal .modal-body').html(html);
            $('#informationmodal').modal('show');
        }
    })
});

其他注意事项

  • 如果一定要保留原Blade的服务端@foreach写法,首次加载模态框所在页面时,路由对应的控制器必须传入$users变量,哪怕传空集合$users = collect()避免未定义错误。
  • 控制器中查询单条数据建议变量名用单数$user,避免和集合混淆。
  • 检查路由配置是否正确匹配/search/{id}/searchInfo路径,请求方法和AJAX设置一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:36:02