JavaScript使用cookie示例
在此示例中,我们将设置cookie的名称。
<head>
<script type="text/javascript">
function WriteCookie() {
if (document.myform.customer.value == "") {
alert("值不能为空");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
alert("Cookies name : " + "name=" + cookievalue);
}
</script>
</head>
<body>
<form name="myform" action="">
Enter name:
<input type="text" name="customer"
<input type="button" value="Set Cookie" onclick="WriteCookie();"
</form>
</body>
</html>
在以下以下示例中,我们将获得cookie的名称。
<html>
<head>
<script type="text/javascript">
function ReadCookie() {
var allcookies = document.cookie;
alert("All Cookies : " + allcookies);
//Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
//Now take key value pair out of this array
for (var i = 0; i < cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"
</form>
</body>
</html>
在此示例中,我们将设置cookie的到期日期。
<html>
<head>
<script type="text/javascript">
function WriteCookie() {
var now = new Date();
now.getDate(now.getDate() + 1);
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie = "name=" + cookievalue;
document.cookie = "expires=" + now.getGMTString() + ";"
alert("Setting Cookies : " + "name=" + cookievalue);
}
</script>
</head>
<body>
<form name="formname" action="">
Enter name:
<input type="text" name="customer"
<input type="button" value="Set Cookie" onclick="WriteCookie()"
</form>
</body>
</html>
在此示例中,我们将删除到cookie。
<html>
<head>
<script type="text/javascript">
function WriteCookie() {
var now = new Date();
now.setMonth(now.getMonth() - 1);
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie = "name=" + cookievalue;
document.cookie = "expires=" + now.getGMTString() + ";"
alert("Setting Cookies : " + "name=" + cookievalue);
}
</script>
</head>
<body>
<form name="formname" action="">
Enter name:
<input type="text" name="customer"
<input type="button" value="Set Cookie" onclick="WriteCookie()"
</form>
</body>
</html>
Cookie是存储网页上用户信息的变量。
用户可以访问同一网页或者下一页的信息。
换句话说,Cookie是一个小型信息存储,由客户端计算机上的Web浏览器中的文本文件中可以检索后者。
javascript客户端或者服务器端可以请求用于存储cookie的Web浏览器。
Cookie Information Store作为名称值对。
JavaScript提供名称"Document.Cookie"属性,以便操纵客户端上的cookie。
- 名称 - 值:-EVERY Cookie具有存储实际信息的名称值,我们将在读出Cookie信息时搜索此名称。
- 到期日: - 每Cookie都有垃圾的Cookie的到期日。如果我们不会设置到期日,那么Cookie将在关闭浏览器时删除。
- 域和路径: - 每个cookie都有一个域和路径。域介绍应该发送cookie域的浏览器。如果未指定它,它将成为设置cookie的页面的域。
日期:2020-04-11 23:04:36 来源:oir作者:oir
