我有一些JavaScript代码,设置一个cookie,当我尝试读取该cookie与PHP它说,它是未定义的。阅读与PHP的Javascript cookie
Notice: Undefined index: scorecount in C:\xampp\htdocs\Contest\score.php on line 44
我使用xamp在我的电脑上运行并测试php,这可能是它不读取cookie的原因吗?
这里是我的代码
<!DOCTYPE html>
<html>
<head>
<title>PHP Written Test</title>
</head>
<body style="background-color:#ADD8E6; margin-left:25%;">
<?php include 'variables.php';?>
<?php include 'functions.php';?>
<?php
session_start();
$x = 1;
$y = 0;
$score = 0;
while ($x <= 20) {
$a = $_POST["question" . $x];
$b = $_SESSION['correct'][$y];
$c = $_SESSION['question'][$y];
if (trim($a) == trim($b)){
$score++;
} else {
echo "$c<br>Your answer was: $a<br>The correct answer is: $b<br><br>";
}
$x++;
$y++;
}
echo "$score/20";
echo $_COOKIE["scorecount"];
?>
</body>
</html>
我会发布图片,以证明该Cookie设置正确,但是我没有足够的代表处。 当我查看我的网络浏览器中的所有cookie时,cookie“scorecount”就在那里,并且设置正确,如果有人能够告诉我我做错了什么,那将是非常感谢!
我的JS是设置cookie
function getCookie(c_name)
{
alert("Im in getCookie");
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
alert("Im in setCookie ");
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : ";
expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
alert("Cookie Set");
}
function checkCookie(end)
{
alert("Im in checkCookie");
document.getElementById('full').ondragstart = function noDrag() { return false; };
var score=getCookie("scorecount");
if (score!=null && score!="")
{
if(end == 'yes')
{
score = score - 1;
return score;
alert("Your score is " + score);
}
else
{
score=1;
if (score!=null && score!="")
{
setCookie("scorecount",score);
//alert("Your score is " + score);
}
}
}
function correct(pgnmbr)
{
var val;
val = getCookie('scorecount');
val = parseInt(val)+ 1;
setCookie('scorecount',val);
location.href = loc();
alert(val);
}
function correct2(pgnmbr)
{
var val;
val = getCookie('scorecount');
val = parseInt(val)+ 1;
setCookie('scorecount',val);
location.href = loc2();
}
var clicks = 0;
function wrong(pgnmbr)
{
clicks++;
if(clicks < 3)
{
alert("wrong try again");
}
else
{
alert("you have exceeded your amount of trys");
location.href = loc();
}
}
document.getElementsByClassName('box1')[0].addEventListener('click', correct, false);
document.getElementsByClassName('bg')[0].addEventListener('click', wrong, false);
检查它是否首先通过标头 – zerkms
你可以发布你的js代码来设置cookie吗? – Class
我加了我的JS .. –