JavaScript创建、读取和删除cookie(2)

<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.toUTCString() + ";" document.write ("Setting Cookies : " + "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>

运行:

JavaScript创建、读取和删除cookie

删除 cookie

删除 cookie 非常简单,不必指定 cookie 值:直接把 expires 参数设置为过去的日期即可:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=https://www.jb51.net/;";

应该定义 cookie 路径以确保删除正确的 cookie。如果不指定路径,有些浏览器不会让咱们删除 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.toUTCString() + ";" document.write("Setting Cookies : " + "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>

代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/eccfcb016b2481e358145e6e67636ea4.html