我尝试在 Javascript 和 Jquery 中设置和获取 Cookie,但这两种方法都返回null 。我的代码看起来正确,但我不知道为什么它对我不起作用。
厨师.js
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}
function deleteCookie(name) {
setCookie(name,"",-1);
}
和我的 html 页面:
fin.html:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="cook.js"></script>
</head>
<body>
<a id="setcookie" href="fin2.html">SET COOKIE</a>
<script>
$("#setcookie").click(function() {
// Using javascript function
setCookie("mycookie", "itsvalue", 1) ;
// Using jQuery plugin
$.cookie('myCookie2': "myValue");
});
</script>
</body>
</html>
fin2.html
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="cook.js"></script>
</head>
<body>
<a id="get" href="#">YOO</a>
<script>
$("#get").click(function() {
alert(getCookie("mycookie")) ;
alert($.cookie('myCookie')) ;
}) ;
</script>
</body>
</html>
但它使用 jquery 插件和 javscript 的函数返回 null。你对这个问题有什么想法吗?十分感谢 :)