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

Laravel/Google API/Ajax:拖拽标记更新经纬度遇500内部服务器错误

Laravel Ajax提交Google地图拖拽坐标时500错误排查

我在使用Ajax将Google地图标记拖拽后的坐标发送至Laravel控制器时遇到500内部服务器错误。已配置POST路由update-marker-position,请求中也携带了csrf_token,但问题依然存在。

相关代码

web.php路由配置

Route::post('/update-marker-position', [MarkerController::class, 'updatePosition'])->name('update-marker-position');

前端Ajax代码

google.maps.event.addListener(marker, 'dragend', function (event) {
    const newLat = event.latLng.lat();
    const newLng = event.latLng.lng();
    const markerTitle = marker.getTitle();
   

    $.ajax({
        method: "POST",
        url: '{{ route('update-marker-position') }}',
        data: {
            _token: '{{ csrf_token() }}',
            title: markerTitle,
            lat: newLat,
            lng: newLng
        },
        success: function (response) {
            console.log('Successfully updated:', response);
        },
        error: function (error) {
            console.error('Error:', error);
        }
    });

    // console.log('Shop:', markerTitle,' Latitude: ', newLat,' Longitude: ', newLng);
});

错误信息

500 (Internal Server Error)

排查步骤

  • 查看Laravel详细错误日志
    500是通用错误提示,直接去storage/logs/laravel.log找具体报错内容,比如模型不存在、字段验证失败、数据库连接异常等,这是最快定位问题的方式。

  • 检查控制器updatePosition方法

    • 确认MarkerController已正确引入到web.php中
    • 检查方法是否正确接收title、lat、lng参数,有没有做参数验证
    • 核对数据库操作逻辑:模型是否存在、字段名是否匹配、有没有未捕获的异常
  • 验证请求参数是否正常传递
    在控制器方法开头添加日志输出,确认参数是否接收成功:

    public function updatePosition(Request $request)
    {
        \Log::info('Received data:', $request->all());
        // 后续业务逻辑
    }
    

    之后查看日志,确认title、lat、lng是否都正确传至后端。

  • 确认CSRF令牌有效性
    虽然已手动传递_token,可以换一种方式验证:在页面头部添加meta标签

    <meta name="csrf-token" content="{{ csrf_token() }}">
    

    然后在Ajax请求前全局设置请求头:

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    

    避免手动传递令牌可能出现的渲染问题。

  • 核对路由命名空间与控制器路径
    确保MarkerController的命名空间正确,比如控制器在App\Http\Controllers下时,路由文件顶部需添加use App\Http\Controllers\MarkerController;。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:42:34