Javascript设置cookie和获取cookie
生活随笔
收集整理的這篇文章主要介紹了
Javascript设置cookie和获取cookie
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
1. 設置cookie
function setCookie (name, value, expireTime) {var date = new Date();date.setTime(Number(date) + expireTime); //獲取距離標準時間零點對應的數(shù)字(毫秒級)document.cookie = name + "=" + encodeURI(value) + ((expireTime == null) ? "" : ";expires=" + date.toGMTString()); }2. 獲取cookie
function getCookie (name) {if(document.cookie.length > 0){c_start = document.cookie.indexOf(name + "="); //在document.cookie字符串中查找字符串name=,返回的初始位置,找不到會返回-1if(c_start != -1){c_start = c_start + name.length + 1;c_end = document.cookie.indexOf(";", c_start); //在document.cookie字符串中,從c_start位置開始找字符串“;“,找不到會返回-1if(c_end == -1){ //如果只有一組數(shù)據(jù),則上一行會找不到“;”,返回c_end=-1c_end = document.cookie.length;}return decodeURI(document.cookie.substring(c_start, c_end)); //獲取name對應的value值}}return ""; }3.傳入?yún)?shù),測試
setCookie("張三", "25", 1*24*60*60*1000) //設置cookie,保存時間為1天 setCookie("lisi", "26", 1*24*60*60*1000) document.write("張三=" + getCookie("張三") + "<br />"); document.write("lisi=" + getCookie("lisi") + "<br />");?4.結(jié)果輸出
5.附錄(完整的html代碼)
<!DOCTYPE html> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"> <head><script type="text/javascript">function setCookie (name, value, expireTime) {var date = new Date();date.setTime(Number(date) + expireTime); //獲取距離標準時間零點對應的數(shù)字(毫秒級)document.cookie = name + "=" + encodeURI(value) + ((expireTime == null) ? "" : ";expires=" + date.toGMTString());}function getCookie (name) {if(document.cookie.length > 0){c_start = document.cookie.indexOf(name + "="); //在document.cookie字符串中查找字符串name=,返回的初始位置,找不到會返回-1if(c_start != -1){c_start = c_start + name.length + 1;c_end = document.cookie.indexOf(";", c_start); //在document.cookie字符串中,從c_start位置開始找字符串“;“,找不到會返回-1if(c_end == -1){ //如果只有一組數(shù)據(jù),則上一行會找不到“;”,返回c_end=-1c_end = document.cookie.length;}return decodeURI(document.cookie.substring(c_start, c_end)); //獲取name對應的value值}}return "";}setCookie("張三", "25", 1*24*60*60*1000) //設置cookie,保存時間為1天setCookie("lisi", "26", 1*24*60*60*1000)document.write("張三=" + getCookie("張三") + "<br />");document.write("lisi=" + getCookie("lisi") + "<br />");</script> </head> <body> </body> </html>?
轉(zhuǎn)載于:https://my.oschina.net/u/3640519/blog/1537074
總結(jié)
以上是生活随笔為你收集整理的Javascript设置cookie和获取cookie的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用spring mail发送html邮
- 下一篇: 使用 docker 搭建 web 服务环