有trim的代码: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>菜鸟教程</title> </head> <head> <script> function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } function getCookie(cname){ var name = cname + "="; var ca = document.cookie.split(‘;‘); for(var i=0; i<ca.length; i++) { // alert("*"+ca[i]+"*"); // ca[i] = "test"; var c = ca[i].trim(); // alert("*"+c+"*"); // var c = ca[i]; if (c.indexOf(name)==0) return c.substring(name.length,c.length); } return ""; } function checkCookie(){ var user=getCookie("username"); if (user!=""){ alert("Welcome again " + user); } else {
user = prompt("Please enter your name:",""); if (user!="" && user!=null){ setCookie("username",user,30); } } } </script> </head>
<body onload="checkCookie()"></body> </html>
无trim的代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>菜鸟教程</title> </head> <head> <script> function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } function getCookie(cname){ var name = cname + "="; var ca = document.cookie.split(‘;‘); for(var i=0; i<ca.length; i++) { // alert("*"+ca[i]+"*"); // ca[i] = "test"; // var c = ca[i].trim(); // alert("*"+c+"*"); var c = ca[i]; if (c.indexOf(name)==0) return c.substring(name.length,c.length); } return ""; } function checkCookie(){ var user=getCookie("username"); if (user!=""){ alert("Welcome again " + user); } else {
user = prompt("Please enter your name:",""); if (user!="" && user!=null){ setCookie("username",user,30); } } } </script> </head>