如何保存WordPress cookie,以便仅使用JavaScript和Ajax使用loggedin,而无需任何插件



我只是尝试使用AJAX登录WordPress。这是我的代码

var username = data.username;
var password = data.password;
var wp_login_url = "http://local_Ip/api/user/generate_auth_cookie/?username=" +username + "&password=" + password + "&insecure=cool";
$.ajax({
        url: wp_login_url,
        type: "GET",
        success: function (data, status) {
          // if status = "okey"
         console.log("Success!!");
         console.log(data);
         console.log(status);
         // write code here to store the cookie
         // do other task once used is logged in.
        }
      });

它运行良好,我也得到了回应。这是我收到的数据。

{

  "status": "ok",
  "cookie": "some_name|1489727386|JpJ5CP4tafjsvcmwKIgSwF3n0YcceHHp951RQ5pL66h|72f3c19d3012f907a2d9ca65c09d068f7f135bc9dd58910521f274e6156613eb",
  "cookie_name": "wordpress_logged_in_ea481ff90802a841ac44175284812226",
  "user": {
    "id": 60,
    "username": "some_name",
    "nicename": "some_name",
    "email": "9**********@something.org",
    "url": "",
    "registered": "2017-03-02 11:28:34",
    "displayname": "some_name",
    "firstname": "",
    "lastname": "",
    "nickname": "",
    "description": "",
    "capabilities": "",
    "avatar": null
  }
}

我想使用JavaScript(无PHP)将Cookie存储在浏览器中,以便将用户登录到WordPress,然后完成其他一些JavaScript任务。我是新手。我不太了解这一点。

格式设置cookie是

    document.cookie="cookie_name=cookie_value; expires=proper date format(UTC); path=/";

为了设置cookie,您需要定义功能

   function setCookie(cookie_name,cookie_value,expiry_date){
       var date = new Date();
       date.setTime(date.getTime() + (expiry_date*24*60*60*1000));
       var expires = "expires="+ date.toUTCString();
       document.cookie = cookie_name+ "=" + cookie_value+ ";" + expires + ";path=/";
  }

这设置了您的cookie。现在要获取cookie,您需要定义另一个功能

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

现在您可以在AJAX成功函数中使用SET函数。

    $.ajax({
    url: wp_login_url,
    type: "GET",
    success: function (data, status) {
      // if status = "okey"
     console.log("Success!!");
     console.log(data);
     console.log(status);
     // write code here to store the cookie
     this.setCookie(data.cookie_name,data.cookie,expiryDate);//expiryDate is any date you want to get the cookie expired on.
     // do other task once used is logged in.
    }
  });

删除cookie将到期日期作为过去的日期。浏览器看到cookie已过期并删除它。希望有帮助。:)

最新更新