创建一个欢迎 cookie

  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. function getCookie(c_name)
  5. {
  6. if (document.cookie.length>0)
  7. {
  8. c_start=document.cookie.indexOf(c_name + "=")
  9. if (c_start!=-1)
  10. {
  11. c_start=c_start + c_name.length+1
  12. c_end=document.cookie.indexOf(";",c_start)
  13. if (c_end==-1) c_end=document.cookie.length
  14. return unescape(document.cookie.substring(c_start,c_end))
  15. }
  16. }
  17. return ""
  18. }
  19.  
  20. function setCookie(c_name,value,expiredays)
  21. {
  22. var exdate=new Date()
  23. exdate.setDate(exdate.getDate()+expiredays)
  24. document.cookie=c_name+ "=" +escape(value)+
  25. ((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
  26. }
  27.  
  28. function checkCookie()
  29. {
  30. username=getCookie('username')
  31. if (username!=null && username!="")
  32. {alert('Welcome again '+username+'!')}
  33. else
  34. {
  35. username=prompt('Please enter your name:',"")
  36. if (username!=null && username!="")
  37. {
  38. setCookie('username',username,365)
  39. }
  40. }
  41. }
  42. </script>
  43. </head>
  44. <body onLoad="checkCookie()">
  45. </body>
  46. </html>