您的位置:首页 > Web前端 > JavaScript

Javascript如何直接读取cookies子键值?

2012-12-03 17:24 302 查看
需要在服务器端创建多值cookie,类似:

HttpCookie aCookie = new HttpCookie(“userInfo”);

aCookie.Values["userName"] = admin”;

aCookie.Values["lastVisit"] = DateTime.Now.ToString();

aCookie.Expires = DateTime.Now.AddDays(1);

Response.Cookies.Add(aCookie);

在前端aspx中通过js直接读取userInfo的某个值,比如:getCookie(“userName”),应该怎么来实现?

除了先在服务器端Request后,再在js中通过<%=%>访问之外,类似下面,有没第二种方法,google后也没有更好的方法!

.cs中

HttpCookie aCookie = Request.Cookies["userInfo"];

string userName=aCookie.Values[userName];

string lastVisit=aCookie.Values[lastVisit];

js文件中:

var userName=<%=userName%>

答案:先读到主键,然后split,如下详细的代码:

JScript code:

function getCookie(name) {

var arr = document.cookie.match(new RegExp(“(^| )userInfo=([^;]*)(;|$)”));

if (arr != null) {

arr = unescape(arr[2]).split(“&”);

for (x in arr)

if (arr[x].split(“=”)[0] == name) {

return arr[x].split(“=”)[1];

}

}

else {

return “”;

}

}

alert( getCookie(“userName”))

JScript code:

function getCookie(key, name) {

var arr = document.cookie.match(new RegExp(“(^| )” + key + “=([^;]*)(;|$)”));

if (arr != null) {

arr = unescape(arr[2]).split(“&”);

for (x in arr) {

if (arr[x].split(“=”)[0] == name) {

return arr[x].split(“=”)[1];

}

}

}

return “”;

}

alert(getCookie(“userInfo”, “userName”))
alert(getCookie(“userInfo”, “lastVisit”))

此文由Web开发之答疑解惑源整理,若需转载,请注明原文(Javascript如何直接读取cookies子键值?)出处:http://www.znjcx.com/html/y2012/1634_javascript-how-to-read-cookies-child-key-values-directly.html,谢谢!

更多热门文章:

1.如何实现点击获取已取得的值?

2.如何用js代码实现验证输入框为空?

3.解决js在google,firfox下出现的bug

4.关于Repeater绑定数据中关键字高亮的问题

5.如何实现将创建的多个DIV用按钮关闭?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐