[英]Read a Javascript cookie with PHP
我有一些設置cookie的javascript代碼,當我嘗試用php讀取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設置正確,但是我沒有足夠的代表。 當我在Web瀏覽器中查看所有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);
好吧,我顯然解決了我的問題,您只能讀取在同一域上設置的cookie。#Duh#Noobie謝謝你們的建議!
嘗試將ajax調用的cookie內容發送給您要用來讀取cookie的php函數,祝您好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.