JS set method to get cookies _javascript tips

Source: Internet
Author: User
Tags set cookie

Combining the JavaScript authority guide with the data collected on the Web during project development, two methods of setting up and getting cookies were sorted out.

Copy Code code as follows:

<script>

Set Cookie Method One
function Setcookie (name,value) {
var exp = new Date ();
Exp.settime (Exp.gettime () + 1*60*60*1000);/valid for 1 hours
Document.cookie = name + "=" + Escape (value) + "expires=" + exp.togmtstring ();
}

* * Access to the cookie is generally easy to inject characters to encode, the corresponding in the acquisition of cookies to decode, there are many ways to encode, there is time to write a blog about encoding and decoding * *

Set Cookie method two to store cookies directly
Document.cookie = "homepage = http://www.jb51.net";

/*-------------------------------------------------------------------------------------------------------*/

A method of taking cookies function
function GetCookie (name) {

var arr = Document.cookie.match (New RegExp ("(^|)" +name+ "= ([^;] *)(;|$)"));

if (arr!= null)

Return unescape (arr[2]);

return null;

}

Method of fetching Cookies function two
function GetCookie (key) {
if (key==null)
return null;
if (Object.prototype.toString.call (key) = = ' [Object String] ' | | Object.prototype.toString.call (key) = = ' [object number] ')
{
var arrstr = Document.cookie.split (";");
for (var i= 0;i<arrstr.length;i++) {
var temp = arrstr[i].split ("=");
if (Temp[0]==key)
Return unescape (temp[1]);
}
return null;
}
return null;
}

</script>


In learning a lot of JS methods encountered will not be on the Internet to find information, until mastered.

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.