You need to enable JavaScript to run this app. PHP foreach循环中使用AJAX更新表格td值异常问题排查
优惠活动
大模型
产品
解决方案
定价
更多

PHP foreach循环中使用AJAX更新表格td值异常问题排查

问题原因

  1. 重复ID与全局选择器错误:所有更新按钮使用相同的id="VerifyBtn",不符合HTML ID唯一规范;使用$("input[name=phone_id]").val()获取值时,jQuery默认只返回匹配到的第一个元素的值,所以永远拿到第一行的phone_id。
  2. Blade渲染变量固化:JS代码中的{{$phone->phone_id}}是服务端渲染的,foreach循环结束后$phone变量指向最后一条遍历的记录,所以JS代码里写死了最后一行的输入框name后缀,永远读取最后一行的账号、描述、user_id值。
  3. 点击事件无上下文绑定:postData()调用时没有传入当前行的标识,JS无法识别点击的是哪一行的按钮。

修正方案

步骤1:修改Blade表格代码

去掉重复ID,给按钮绑定自定义属性存行标识,用class区分输入框:

<div class="row">
    <div class="col-12 col-md-8 offset-md-2 text-center mt-30 rename">
        <!-- 记得在页面head加CSRF元标签,否则AJAX POST会报419错误 -->
        <!-- <meta name="csrf-token" content="{{ csrf_token() }}"> -->
        <table class="table">
            <thead>
            <tr>
                <th scope="col">Number</th>
                <th scope="col">Description</th>
                <th scope="col">Balance</th>
                <th scope="col">Actions</th>
            </tr>
            </thead>
            <tbody>
            @foreach ($phones as $phone)
                <tr>
                    <th scope="row"><input value="{{$phone->phone_account}}" type="text" class="phone-account-input"></th>
                    <td><input value="{{$phone->description}}" type="text" class="description-input"></td>
                    <td><input value="{{ $phone->balance }}" disabled></td>
                    <td>
                        <!-- 用data属性存当前行的ID参数,去掉onclick绑定 -->
                        <input type="button" class="btn btn-profile update-btn" value="Update" 
                               data-phone-id="{{$phone->phone_id}}" 
                               data-user-id="{{$phone->user_id}}">
                        <a href="{{ route('phonedelete', ['id'=>$phone->phone_id]) }}" role="button" class="btn btn-profile">Delete</a>
                    </td>
                </tr>
            @endforeach
            </tbody>
        </table>
        <div id="success" style="display: none"></div>
    </div>
</div>

步骤2:修改AJAX代码

用事件委托绑定按钮点击事件,通过当前点击的按钮定位所在行,读取对应行的参数:

// 全局绑定所有更新按钮的点击事件,不需要单独写onclick
$('.update-btn').on('click', function() {
    // 定位当前点击按钮所在的行
    const currentRow = $(this).closest('tr');
    // 读取按钮绑定的行ID参数
    const phoneId = $(this).data('phone-id');
    const userId = $(this).data('user-id');
    // 只读取当前行的输入框值
    const phoneAccount = currentRow.find('.phone-account-input').val();
    const description = currentRow.find('.description-input').val();
    
    $.ajax({
        url: '{{ route('update_phone.post')}}',
        type: 'POST',
        data: {
            _token: $('meta[name="csrf-token"]').attr('content'), // 必须传CSRF token
            phone_account: phoneAccount,
            description: description,
            user_id: userId,
            id: phoneId,
        },
        cache: false,
        success: function (data) {
            console.log(data)
            if (data == 'success') {
                $('#success').show().html('phone account successfully updated.');
            }else{
                alert('Error occurred, please try again later...');
            }
        }
    });
})

步骤3:后端代码优化(可选)

建议返回规范的JSON响应,原来的逻辑无需修改:

public function update_phone(Request $request){
    $id = $request->id;
    $user_id = $request->user_id;
    $phone_acc = $request->phone_account;
    $phone_desc = $request->description;
    $date = date("Y-m-d H:i:s");
    DB::table('phone_details')
        ->where('user_id', $user_id)
        ->where('phone_id', $id)
        ->update(['phone_account' => $phone_acc,
                  'description' => $phone_desc,
                  'updated_at' => $date]);

    return response()->json('success');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 04:57:02