|
2005/10/13
■ちょっとJavaScriptでCookieを使いたい
よくよく自分のホームページをみたら、アクセスカウンターのCGIでCookieを見たり書いたりしてた。CGIアクセス毎回やってんじゃん・・・。
サーバ負担を減らすべくJavaScriptの利用を考え、Cookieのテストしてみた。
<!-- ./sample01.html -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title></title>
<script type="text/javascript" language="JavaScript">
<!--
function setCookie() {
delTime = new Date;
delTime.setMinutes(delTime.getMinutes() + 1); //有効期間1分
document.cookie = "A=0;expires=" + delTime.toGMTString();
document.cookie = "B=1;expires=" + delTime.toGMTString() + ";path=/~kshrn";
document.cookie = "C=2;expires=" + delTime.toGMTString() + ";path=/~kshrn/testc";
}
-->
</script>
</head>
<body>
TEST_HTML
<br>
<input type="button" name="testbtn" value="setCookie" onclick="setCookie();">
<br>
<script type="text/javascript" language="JavaScript">
<!--
document.write(document.cookie);
-->
</script>
</body>
</html>
<!-- ./testc/sample02.html -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title></title>
<script type="text/javascript" language="JavaScript">
<!--
function setCookie() {
delTime = new Date;
delTime.setMinutes(delTime.getMinutes() + 1); //有効期間1分
document.cookie = "X=8;expires=" + delTime.toGMTString();
document.cookie = "Y=9;expires=" + delTime.toGMTString() + ";path=/~kshrn";
document.cookie = "Z=10;expires=" + delTime.toGMTString() + ";path=/~kshrn/testc";
}
-->
</script>
</head>
<body>
TEST_HTML 2
<br>
<input type="button" name="testbtn" value="setCookie" onclick="setCookie();">
<br>
<script type="text/javascript" language="JavaScript">
<!--
document.write(document.cookie);
-->
</script>
</body>
</html>
pathの使い方が今回のメイン。まずは表示。
/testc01.htmlのほうのボタンをクリック。そして両方のページを更新。
/testc/testc02.htmlのほうのボタンをクリック。そして両方のページを更新。
こっちはA,B,Y
こっちは全部保存できてる。(A,B,C,X,Y,Z)
つまりこのカサハランのホームページ内で共通にCookieを使いたいなら、
path=/~kshrn";
とすればいいわけか。ドメインhttp://www5d.biglobe.ne.jp/が基準となるわけね。
ということで、もう寝ます。
|