douzi4724
2019-07-04 15:54 阅读 79

Laravel 5.8登录后重定向

In my Laravel application there is the default login page aswell as a login form inside a dropdown. As I have it set up now, after a successfull login a user is redirected to the index page, however, If a user uses the login form in the dropdown I want him to stay on the page he is already.

Is there a better practice than adding a seperate method for logging in via the dropdown?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • dqt83336 dqt83336 2019-07-04 16:32

    You can use axios or ajax to login and stay on the page.

    Example for axios, in your script write something like this

    $("body").on("submit", "#login-form", function (e) {
        var action = $(this).attr("action"); // your login url
    
        e.preventDefault();
    
        axios.post(action, $(this).serialize())
         .then(function (response) {
            // do something from the response
            // i.e. display error or update navbar to logged in view
         })
         .catch(function (error) {
            // handle error here
         });
    });
    

    Example for ajax, in your script write something like this

    $("#login-form").submit(function(event){
        event.preventDefault(); //prevent default action 
        var post_url = $(this).attr("action"); //get form action url
        var request_method = $(this).attr("method"); //get form GET/POST method
        var form_data = $(this).serialize(); //Encode form elements for submission
    
        $.ajax({
            url : post_url,
            type: request_method,
            data : form_data,
            beforeSend: function() {
                // show loading or whatever
            },
            success: function(data) {
                // do something from the response
                // i.e. display error or update navbar to logged in view
            },
            error: function(xhr) { // if error occured            
                var status = xhr.statusText;
                var response = JSON.parse(xhr.responseText);
    
                // handle error here                       
            }
        });
    });
    

    In both examples, I assume that you will have a login form with an ID login-form

    点赞 评论 复制链接分享

相关推荐