jQuery Operation cookie

  • 2021-07-09 06:54:11
  • OfStack

During the development of web, if one part of the website information is stored in cookie and interacts with the server, the foreground sometimes encounters the situation that the information in cookie needs to be operated. A most typical example is to judge whether the user has logged in to the currently visited website in the foreground.

You can use js native code to operate cookie, but for those who are used to using jquery in the foreground, it is best to have a method directly extended to jquery instance object to unify 1 operation style, and record a simple scheme with personal feeling here.


$.extend({
cookie : function(name, val) {
if (!val) {
var a = document.cookie.match(RegExp("(^|\s*)" + name + "=([^;]*)(;|$)"));
return a ? decodeURIComponent(a[2]) : null;
} else {
document.cookie = name + "=" + escape(val);
}
},
removeCookie : function(name) {
var expires = new Date();
expires.setTime(expires.getTime() - 1);
document.cookie = name + "=;expires=" + expires.toGMTString();
}
}); 

In this way, it will be unified in style. Take login as an example:

Value-$. cookie ("logonFlag");

Assignment-$. cookie ("logonFlag", true);

Delete-$. removeCookie ("logonFlag");

The cookie method can also provide a third parameter extension when used as an assignment function, and the user can provide optional attributes and assign values to the cookie that needs to be assigned.

In actual use, I found that there are some restrictions on the assignment/value here, and some special symbols (such as " > "," < "Symbol) does not encode/decode effectively, but is generally easy to use.


Related articles: