我尝试使用提示让某人输入值,将该值转换为Cookie,然后使用链接将该人重定向到第二页,其中将显示其Cookie值。我遇到的问题是,无论我输入什么,有问题的cookie都会继续返回null。任何帮助,将不胜感激!
这是一个Javascript代码。
首页(提示页面)
<!DOCTYPE html>
<html>
<head>
<title>Event Handlers</title>
<script>
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = newDate();
date.setTime( date.getTime() + (days*24*60*60*1000));
var expires = date.toGMTString ();//code
}
else var expires = "";
cookieString = name + "=" + escape(value);
if (expires) cookieString += ";expires=" + expires;
if (path) cookieString += "; path=" + escape (path);
if (domain) cookieString += "; domain=" + escape (domain);
if (secure) cookieString += "; secure";
document.cookie = cookieString
}
function getCookie(name) {
var nameEquals = name + "=";
var crumbs = document.cookie.split(';');
for (var i = 0; i < crumbs.length; i++) {
var crumb = crumbs[i];
if (crumb.indexOf(nameEquals) == 0) {
return unescape(crumb.substring(nameEquals.length, crumb.length));
//code
}
}
return null;
}
function deleteCookie(name) {
createCookie(name,"",-1);
//code
}
</script>
<script>
window.onload = function() {
var cookievalue = prompt("Cookie Value:");
createCookie("myCookieData", cookievalue);
}
</script>
</head>
<body>
<a href="/cookietest2">Go to Cookie Test Page 2</a>
</body>
</html>
&#13;
第二页(显示Cookie页面)
<!DOCTYPE html>
<html>
<title>Cookie Testing</title>
<head>
<script>
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = newDate();
date.setTime( date.getTime() + (days*24*60*60*1000));
var expires = date.toGMTString ();//code
}
else var expires = "";
cookieString = name + "=" + escape(value);
if (expires) cookieString += ";expires=" + expires;
if (path) cookieString += "; path=" + escape (path);
if (domain) cookieString += "; domain=" + escape (domain);
if (secure) cookieString += "; secure";
document.cookie = cookieString
}
function getCookie(name) {
var nameEquals = name + "=";
var crumbs = document.cookie.split(';');
for (var i = 0; i < crumbs.length; i++) {
var crumb = crumbs[i];
if (crumb.indexOf(nameEquals) == 0) {
return unescape(crumb.substring(nameEquals.length, crumb.length));
//code
}
}
return null;
}
function deleteCookie(name) {
createCookie(name,"",-1);
//code
}
</script>
<script>
window.onload = function () {
document.getElementById("output").innerHTML = "Your cookie value: " + getCookie("myCookieData");
}
</script>
</head>
<body>
<a href="/hour">Back to Cookie Test Page 1</a><br />
<div id="output"></div>
</body>
</html>
&#13;
此外,如果有人可以提供有关如何向第二页添加按钮以从第一页删除cookie的提示,那也将非常感谢!但就目前而言,我只是想弄明白为什么我的cookie一直被归还为null。提前谢谢!
答案 0 :(得分:0)
某些浏览器的本地文件中不允许使用Cookie。因此,如果您正在使用本地文件 - 请尝试将这些文件上传到服务器并再次尝试。适合我。
要添加Cookie删除按钮,您可以使用:
<input type="button" onClick="deleteCookie('myCookieData')" />