js设置cookie

来源:互联网 发布:泰国直播软件 编辑:程序博客网 时间:2024/06/05 15:01

本文讲述基本js操作cookie,同时解决两个问题:1.一个页面设置后,其他页面取不到问题。2.json数据存储失败的问题。认真读一下, 后面会解决这两个问题,如果你的cookie设置没成功。注意细节。

不多说上代码:

function getCookie(c_name) {if (document.cookie.length > 0) {c_start = document.cookie.indexOf(c_name + "=")if (c_start != -1) {c_start = c_start + c_name.length + 1c_end = document.cookie.indexOf(";", c_start)if (c_end == -1)c_end = document.cookie.lengthreturn unescape(document.cookie.substring(c_start, c_end))}}return ""}function setCookie(name, value) {var exp = new Date();exp.setTime(exp.getTime() + 3 * 24 * 60 * 60 * 1000); //3天过期  document.cookie = name + "=" + encodeURIComponent(value)+ ";expires=" + exp.toGMTString() + ";path=/";return true;};

以上代码,注意 pah=/ .此处可以解决其他页面取不到本页面设置的cookie问题,理论上同一域名下,cookie是共享,但是默认设置的时候,会加上文件夹。就会出现取不到。


//数据库查询用户信息,并设置到cookie中。window.onload = function() {$.post("queryUserInfo", {}, function(data) {debugger;setCookie("userInfo", JSON.stringify(data));alert(getCookie("userInfo"));window.location = "/GovPlatform/static/view/gov/home.html";});}

取出代码:

var userInfo = JSON.parse(getCookie("userInfo"));



以上代码,是对后台的用户信息,进行获取,然后设置到cookie中,在跳转到一个页面。那个页面自然用上面的getCookie 进行取出。

这里需要注意一个要点,这个data的json是一个对象。 会有“,”。这个“,”是特殊字符,导致不能设置到cookie中,

如果后台是java,会提示这个“that contained an invalid cookie. That cookie will be ignored.Note: further occurrences of this error will be logged at DEBUG level.”

两种解决办法, 一种是将“,”替换掉(replace)。

另一种,使用JSON.stringify(data)就可以了。取出来的时候注意使用JSON.parse(data) 如上图代码。(推荐这种)

原创粉丝点击