在表单提交/登录时使用jquery设置cookie [英] Set cookie using jquery on form submit / log in

查看:59
本文介绍了在表单提交/登录时使用jquery设置cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我不熟悉的事物上寻找方向或输入.我使用登录表单创建了一个两页的网站,该表单使用我创建的正确的访问代码"将用户重定向到第二页.它按预期工作.我想做的是在用jquery或vanilla js登录用户时设置一个cookie,然后检查用户之前是否已经登录以及是否没有重定向回登录表单.我知道我没有尝试任何事情",只是想学习并获得想法或建议

Looking for direction or input on something I'm not familiar with. I created a two page site with a log in form that redirects user to the second page with the correct "access code" I created. It works as expected. What I would like to do is set a cookie when user is logged with jquery or vanilla js, then check if the user has logged in before and if they have not redirect back to log in form. I know I have not "tried anything" but just looking to learn and get an idea or advice

HTML:

<form class="form--log-in" id="log-in-form">
    <div class="form-group">
        <label for="firstName">First Name</label>
        <input type="text" class="form-control" name="firstName" id="firstName" placeholder="First Name">
    </div>
    <div class="form-group">
        <label for="lastName">Last Name</label>
        <input type="text" class="form-control" name="lastName" id="lastName" placeholder="Last Name">
    </div>
    <div class="form-group">
        <label for="userEmail">Email Address</label>
        <input type="email" class="form-control" name="userEmail" id="userEmail" placeholder="Email Address">
    </div>
    <div class="form-group">
        <label for="accessCode">Access Code</label>
        <input type="text" class="form-control" name="accessCode" id="accessCode" placeholder="Access Code">
    </div>
    <div class="form--log-in__submit-container">
        <button type="submit" class="btn button-submit form--log-in__submit" id="form_submit">
            Log in
        </button>
    </div>
</form>

jquery:

      // doc ready
      $(function () {
        checkCookie();
    }


    submitHandler: function (form) {
          var formData = {
            'method': 'register',
            'firstName': $('input[name=firstName]').val(),
            'lastName': $('input[name=lastName]').val(),
            'userEmail': $('input[name=userEmail]').val(),
            'accessCode': $('input[name=accessCode]').val(),
          };


          var validationObj = this;

          $.ajax({
            type: 'POST',
            url: form_submit_endpoint,
            data: formData,

            success: function (res) {
              var parsedResponse = JSON.parse(res);


              if (parsedResponse.status === 'success') {
                console.log('success');

                _siteNS.Utils.setCookie('x-access',true,365);

                logInModal();

              } else if (parsedResponse.status === 'error') {
                validationObj.showErrors({'accessCode': 'Incorrect Access Code.'});
                console.log('error');
              }
            }
          })
        }

    function _readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1, c.length);
                }
                if (c.indexOf(nameEQ) === 0) {
                    return c.substring(nameEQ.length, c.length);
                }
            }
            return null;
        }

        function _setCookie(cookiename, value, numberofdays) {
            var d = new Date();
            d.setTime(d.getTime() + (numberofdays * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toUTCString();
            document.cookie = cookiename + "=" + value + ";" + expires + ";path=/";
        }



    function checkCookie() {
           // set cookie to boolean var
   var myCookie = document.cookie === null;

        //if the cookie is true and location is not the video page set location to video page
        if(myCookie === true && (!location.href.match(/video-page/))){
          window.location.replace('video-page');
        }

        //if the cookie is false and location is not the site root set location to site root
        if(myCookie === false && (!location.href.match(/index/))){
          window.location.replace('index');
        }
      }

推荐答案

这是您的操作方式.

  1. ajax成功后,设置一个本地存储项,例如'isLoggedIn', 'true'
  2. 在全局为每个页面加载的另一个JS文件中,您应检查localstorage标志是否设置为true.
  3. 根据结果重定向到所需页面

注意:上面的方法仅用于了解如何实现身份验证.这绝对是不安全的.您将必须使用诸如JWT之类的身份验证,并在本地主机或cookie中设置令牌,该令牌将针对每个请求发送到服务器.

NOTE: The above method is only to learn about how you can achieve auth. This is definitely not secure. You would have to use some kind of authentication like JWT and set the token in your localhost or cookie that will be sent to the server for each request.

在构建真实的应用程序之前,请务必先阅读有关身份验证的信息.

Please do read about authentication before you build a real world app.

$.ajax({
  type: 'POST',
  url: form_endpoint,
  data: formData,

  success: function(res) {
    var parsedResponse = JSON.parse(res);


    if (parsedResponse.status === 'success') {
      // set localstorage flag if successfully logged in
      // NOTE: this is not secure. You need to have some kind of JWT token to be implemented
      if (typeof(Storage) !== "undefined") {
        localstorage.setItem('isLoggedIn', 'true');
      } else {
        // Sorry! No Web Storage support..
      }

    }
  }
});


// In another JS file that is loaded globally

window.on('load', function() {
  if (typeof(Storage) !== "undefined") {
    const loginStatus = localstorage.getItem('isLoggedIn');

    if (loginStatus === 'true') {
      // redirect him to logged in page
    } else {
      // redirect him to unauthorized in page
    }
  } else {
    // Sorry! No Web Storage support..
  }
})

这篇关于在表单提交/登录时使用jquery设置cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆