【问题标题】:Laravel 5 response not triggering $.ajax({success})Laravel 5 响应未触发 $.ajax({success})
【发布时间】:2015-05-31 04:58:29
【问题描述】:

我有一个带有 jQ​​uery 的 ajax 请求,表单提交,控制器相应地响应 ant 执行所有登录逻辑,但 $.ajax 成功函数没有触发。在两种情况下,错误函数确实会被触发。验证失败或用户输入密码错误。

任何帮助或建议将不胜感激。谢谢。

ajax调用代码:

(function() {
var submitAjaxRequest = function(e) {

    var form = $(this);

    var method = form.find('input[name="_method"]').val() ||  'POST';

    $.ajax({

        type: method,

        url: form.prop('action'),

        data: form.serialize(),

        success: function(data) {
            console.log(data);
            if( data.status === 200 ) {//redirect if not authenticated user.
                $( location ).prop( 'pathname', 'projects' );
                var errors = data.responseJSON;
                console.log(data.responseJSON);
            }
        },
        error: function(data) {
            if( data.status === 401 ) {//redirect if not authenticated user.
                $( location ).prop( 'pathname', 'auth/login' );
                var errors = data.responseJSON;
                console.log(data.responseJSON);
            }
            if( data.status === 422 ) {
            //process validation errors here.
            var errors = data.responseJSON; 

            errorsHtml = '<div class="alert alert-danger"><ul>';

            $.each( errors , function( key, value ) {
                errorsHtml += '<li>' + value[0] + '</li>'; 
            });
            errorsHtml += '</ul></di>';

            $( '#form-errors' ).html( errorsHtml ); 
            } else {

            }
        }
    });

    e.preventDefault();
};

$('form[data-remote]').on('submit', submitAjaxRequest);
})();

以及处理post请求的方法:

public function postLogin(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email', 'password' => 'required',
    ]);

    $credentials = $request->only('email', 'password');

    if ($this->auth->attempt($credentials))
    {
        return response(array('msg' => 'Login Successfull'), 200)
          ->header('Content-Type', 'application/json');
    }

    return response(array('msg' => $this->getFailedLoginMessage()), 401)
          ->header('Content-Type', 'application/json');

    }

【问题讨论】:

    标签: jquery ajax json http laravel


    【解决方案1】:

    我正在使用:

    <button type="submit" onsubmit="validate()" >
    
    function validate()
    {
      ajax call; // it was supporting html5 validation
    }
    

    然后我用了:

    <button type="button" onclick="validate()" >
    
    function validate()
    {
      ajax call; // here it was not supporting html5 validation 
                 //but working for success and error part
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-13
      • 2011-02-22
      • 2021-03-20
      • 2015-08-15
      • 1970-01-01
      • 2015-11-10
      • 2023-03-26
      • 2016-04-18
      • 1970-01-01
      相关资源
      最近更新 更多