我想检查html中是否存在cookie, 这是我的代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="a1">
<p id = "ttttt">a1 test</p>
</div>
<script>
function checkCookie() {
$cookie_name = 'testhastin';
if(!isset($_COOKIE[$cookie_name])) {
document.getElementById("ttttt").innerHTML = "set";
} else {
document.getElementById("ttttt").innerHTML = "not set";
}
}
window.checkCookie();
</script>
</body>
</html>
但是当我运行此页面时,会注意到&#34; a1 test&#34;。 (意思是它不会改为&#34;没有设置&#34;)
我想检查页面上是否存在cookie,如果是,则显示特定内容。
我也试过这段代码,结果是一样的:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="a1">
<p id = "ttttt">a1 test</p>
</div>
<script>
function checkCookie() {
var username = getCookie("testhastin");
if (username != "") {
document.getElementById("ttttt").innerHTML = "set";
} else {
document.getElementById("ttttt").innerHTML = "not set";
}
}
window.checkCookie();
</script>
</body>
</html>
答案 0 :(得分:1)
$_COOKIE
是一个PHP变量。 isset()
是一个PHP函数。你不能在JavaScript中使用它。
至于获取cookie,请使用document.cookiename
// Setting a cookie
document.testhastin= "Akshay";
// Reading a cookie
var val = document.testhastin;
W3Schools链接:https://www.w3schools.com/js/js_cookies.asp