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

Laravel中使用AJAX提交登录表单无法发送数据的问题求助

问题排查及修复方案

1. 重复ID导致取值异常

你的HTML代码中,邮箱和密码的输入框与下方错误提示的small标签使用了相同的ID:

  • 邮箱输入框id="email",对应错误提示small也设置了id="email"
  • 密码输入框id="password",对应错误提示small也设置了id="password"
    DOM规范要求ID全局唯一,重复ID会导致jQuery通过$("#email").val()、$("#password").val()取值时无法正确获取输入框内容,是AJAX提交异常的常见诱因。

修复方案:修改错误提示标签的ID,比如改为email_err_msg、password_err_msg即可。

2. 控制器返回值与前端判断逻辑完全反向

控制器中账号密码验证失败时,返回的是response()->json(['error'=>false]),但前端AJAX的判断逻辑是if(data.error === true)才显示账号密码错误提示,导致验证失败时前端完全没有反馈。

修复方案:修改控制器对应返回逻辑,账号密码错误时返回error = true:

// 原代码
return response()->json(['error'=>false]);
// 替换为
return response()->json(['error'=>true]);

3. Form标签重复定义action属性

你的form标签同时写了两个action属性,属于不规范写法,虽然e.preventDefault()会阻止默认提交行为,但建议清理冗余属性,仅保留需要的路由地址即可:

<!-- 原代码 -->
<form action="javascript:void(0)" id="loginform" action="{{ route('giris') }}" method="post">
<!-- 替换为 -->
<form id="loginform" action="{{ route('giris') }}" method="post">

4. 缺少AJAX错误回调,无法排查请求异常

当前AJAX仅配置了success回调,若请求出现419 CSRF校验失败、500服务器错误、404路由不存在等问题时,没有任何提示,无法定位问题,建议补充error回调:

$.ajax({
    url: "{{ route('giris') }}",
    type:'POST',
    data:{'_token' : '{{ csrf_token() }}', email:email, password:password},
    success: function(data) {
        printMsg(data)
        if(data.status === true)
        {
            window.location.href = '/';
        }
        if(data.error === true){
            $('#mydiv').show()
        }
    },
    // 新增错误回调
    error: function(xhr) {
        console.log('请求错误:', xhr.responseText);
    }
});

5. 记住我功能未生效

当前控制器中auth()->attempt的记住我参数固定为true,没有接收前端用户的勾选状态,若需要实现记住我功能,可补充参数传递:

// AJAX的data部分补充remember参数
data:{
    '_token' : '{{ csrf_token() }}', 
    email:email, 
    password:password,
    remember: $('input[name="remember"]').is(':checked') ? 1 : 0
},

控制器对应修改:

if (auth()->attempt(
    ['email' => $request->input('email'), 'password' => $request->input('password')],
    $request->input('remember')
))

完成以上修改后即可正常使用AJAX登录功能。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:24:05