Example and simple analysis of using JS to get cookie

Source: Internet
Author: User

 

A lot of problems were discovered today when the review new JavaScript code was written. Here is an example of function GetCookie (name) {}.

One of the more typical questions is how to get a value from a cookie using JavaScript. So let's start by looking at what the cookie looks like.
Enter directly in the browser address bar: Javascript:alert (Document.cookie); Enter. (This line of code means to have the browser execute a JavaScript statement: alert (document.cookie);)
The result: uin=webryan; sessionid=10293123834; pgv_send=1; cur_page=index this looks.
Note: 1. There is no space at the beginning, 2. Semicolon followed by a space 3. There is no semicolon at the end. So the way we get cookies is quite clear.

One is to use Document.cookie.split (";") Way to split a string into segments and then iterate through the entire array. Compares each array unit equal to the name on the left side of the equality, and equals the value to the right of the equals sign.

View Plaincopy to Clipboardprint?
    1. function GetCookie (name) {
    2. var arr = document.cookie.split (";");
    3. for (var i=0,len=arr.length;i<len;i++) {
    4. var item = arr[i].split ("=");
    5. if (item[0]==name) {
    6. return item[1];
    7. }
    8. }
    9. return "";
    10. }
[JS]View PlainCopy
  1. function GetCookie (name) {
  2. var arr = document.cookie.split (";");
  3. For (var i=0,len=arr.length;i<len;i++) {
  4. var item = arr[i].split ("=");
  5. if (item[0]==name) {
  6. return item[1];
  7. }
  8. }
  9. return "";
  10. }

The second is to search for the keyword directly in the string. Because the semicolon has a space, plus prevents the search cookie from appearing, the value of "str" is a TEST_STR cookie name. Here we do a filter first. And then find out where Str is, so there's no problem. The specific situation is as follows

View Plaincopy to Clipboardprint?
    1. function getcookie (name) {
    2. var value=
    3. var cookie =  ";" +document.cookie.replace (/;\s+/g,
    4. var pos = cookie.indexof ( ";") +name+if (pos>-1) {
    5. var start = Cookie.indexof (var end = cookie.indexof (
    6. value = unescape (cookie.substring (start+1,end));
    7. return value;
[JS]View PlainCopy
  1. function GetCookie (name) {
  2. var value="";
  3. var cookie = ";" +document.cookie.replace (/;\s+/g,";")  +";"
  4. var pos = cookie.indexof (";"  +name+"=");
  5. if (pos>-1) {
  6. var start = Cookie.indexof ("=", POS);
  7. var end = Cookie.indexof (";", start);
  8. Value = Unescape (cookie.substring (start+1,end));
  9. }
  10. return value;
  11. }

Different methods have different choices at different times. This is Xiao Xiao said the type of problem.

The code that is actually used now is

View Plaincopy to Clipboardprint?
  1. /**
  2. * Cookie-related
  3. */
  4. $.cookie = {
  5. /**
  6. * Read cookies
  7. *
  8. * @param {String} n= name
  9. * @return {String} cookie Value
  10. * @example
  11. * $.cookie.get (' id_test ');
  12. */
  13. Get:function (n) {
  14. var m = document.cookie.match (new RegExp ( "(^|)") +n+"= ([^;] *)(;|$)"));
  15. Return!m? "": unescape (M[2]);
  16. },
  17. /**
  18. * Set Cookies
  19. * @param {String} name Cookie name-Required
  20. * @param {String} value cookie value-Required
  21. * @param domain name of {String} domain
  22. * @param the path of {String} path
  23. * @param {Number} hour survival time, unit: Hours
  24. * @example
  25. * $.cookie.set (' value1 ', ' cookieval ', "id.qq.com", "/test", 24); Set cookies
  26. */
  27. Set:function (name,value,domain,path,hour) {
  28. var expire = new Date ();
  29. Expire.settime (Expire.gettime () + (hour?3600000 * hour:30*24*60*60*1000));
  30. Document.cookie = name + " =" + value + ";" + "expires=" + expire.togmtstring () + "; Path= "+ (Path Path:"/") + "; "+ (domain? ("domain=" + domain + ";"): "");
  31. },
  32. /**
  33. * Delete the specified cookie, the replication is expired!! Note that path is strictly matched,/id is different from/id/
  34. *
  35. * @param {String} name Cookie name
  36. * @param {String} domain
  37. * @param the path of {String} path
  38. * @example
  39. * $.cookie.del (' id_test '); Delete Cookies
  40. */
  41. Del: function (name, domain, path) {
  42. Document.cookie = name + "=; Expires=mon, 1997 05:00:00 GMT; Path= "+ (Path Path:"/") + "; "+ (domain? ("domain=" + domain + ";"): "");
  43. },
  44. /**
  45. * Delete all Cookies--the cookie is not included in this directory for the time being
  46. * @example
  47. * $.cookie.clear (); Delete all Cookies
  48. */
  49. Clear:function () {
  50. var rs = document.cookie.match (new RegExp ("([^;] [^;] *)(?=(=[^;] *) (; |$)) ", " GI " ));
  51. Delete all Cookies
  52. for (var i in rs) {
  53. Document.cookie = rs[i] + "=;expires=mon, Jul 1997 05:00:00 GMT; path=/; " ;
  54. }
  55. },
  56. /**
  57. * UIn-for business, external open source please delete
  58. *
  59. * @return {String} UIn value
  60. * @example
  61. * $.cookie.uin ();
  62. */
  63. UIn:function () {
  64. var u = $.cookie.get ("UIn");
  65. Return!u? Null:parseint (u.substring (1, u.length), ten);
  66. }
  67. };

Example and simple analysis of using JS to get cookie

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.