如果没有设置cookie,本文档如何能够检测到它?

时间:2011-09-23 11:43:07

标签: javascript cookies

这是一个用某些 html文件设置cookie的脚本。

window.onload=init;

function init() {
var userName="";
if(document.cookie != "") {
    username=document.cookie.split("=")[1];
    document.getElementById("name_field").value = username;
}

document.getElementById("name_field").onblur = setCookie;
}

function setCookie() {
var exprDate = new Date();
exprDate.setMonth(exprDate.getMonth() + 6);

var username = document.getElementById("name_field").value;
document.cookie = "username=" + username + ";path=/;expires=" + exprDate.toGMTString();
}

这是另一个带有不同 html文件的脚本(过去没有保存过cookie),用于检查是否有与此文档一起保存的cookie。

window.onload = initTest;

function initTest() {
if(document.cookie == "") alert("No,cookies stored !");
else alert("cookies found !");
}

令我惊讶的是,当我使用第二个脚本运行第二个html文件时,找到了cookie 为什么会这样?如果该文档尚未保存cookie,那么document.cookie != ""会怎样?

1 个答案:

答案 0 :(得分:2)

根据域和/或路径设置Cookie。

示例:

  • http://www.example.com/foo.html Cookie x=x; max-age=3600;http://www.example.com/*处可见,但在http://other.example.com/
  • 处无法显示
  • http://www.example.com/foo.html Cookie x=x; max-age=3600; domain=.example.comhttp://*.example.com/*http://example.com/*
  • 处可见
  • 仅限https协议: Cookie: x=x; max-age=3600; secure
  • 路径可以更改为当前路径或任何父目录。默认路径是当前目录。例如:x=x; max-age=3600; path=/