我正在尝试用cookies做一些事情。现在我只想尝试读取cookie并使用alert(值)在弹出框中显示该值。 我关注的教程是: http://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username
当我将其实现到我的Web应用程序中时,这不起作用。将创建cookie,但阅读部分不知何故不起作用。当我使用Web Developer Toolbar时,我可以看到名为“language”的cookie就在那里。
这是我的Index.aspx中的脚本块
function createCookie() {
var box = document.getElementById("language");
var value = box.options[box.selectedIndex].value;
var name = "language";
var days = 1;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + ";path=/;";
document.cookie = 'language=en; expires=Thu, 2 Aug 2012 20:47:11 UTC; path=/'
window.location = 'http://localhost:57688';
}
function readLanguageCookie() {
var language = getCookie("language");
if (language != null && language != "") {
alert("Language is: " + language);
} else {
language = "en";
if (language != null && language != "") {
setCookie("language", language, 365);
}
}
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
这就是我尝试执行方法的方法
<form method="get" action="http://localhost:57688">
<label for="language">hjhj</label>
<select id="language" onchange="readLanguageCookie()">
<option value="en">English</option>
<option value="nl">Dutch</option>
</select>
</form>
Cookie详情:
Name language
Value en
Host localhost
Path /
Secure No
Expires Thu, 02 Aug 2012 20:47:11 GMT
我在这里做错了什么?
答案 0 :(得分:-1)
可能是硬编码日期的原因?:
document.cookie = 'language=en; expires=Thu, 2 Aug 2012 20:47:11 UTC;