2017-10-04 235 views
-5

我正在一個網站上猜測數字。網站的概要如下所示: enter image description here如何在HTML中打印出cookie值?

在setCookiesA.php,有名爲c(顏色)和MAXNUM存儲(猜測的最大數目)兩個cookie。存儲cookies後,玩家將被重定向到GuessingA.php。的代碼如下所示:

<?php 
    setCookie("c",$_GET["itemChosen"],time()+(86400 * 365), "/"); 
    setCookie("maxNo",$_GET["noGuess"],time()+(86400 * 365), "/"); 
    header("Location:GuessingA.php"); 
?> 

要GuessingA.php後,cookie值顏色應該在句子中被打印出來「你已選擇的信道???爲猜測」(???表示顏色)部分完成的代碼如下所示。

<?php 
    session_start(); 
    if (!isset($_SESSION["ans"])) { 

    } else { 

    } 
    $continue = true; 
?> 
<!DOCTYPE html> 
<html> 
<head> 
    <title> Guessing game </title> 
</head> 
<body> 
    <h1> Welcome </h1> 
    <p> You have chosen the $_COOKIE[c] channel for guessing</p> 

    <h2> The answer </h2> 




    <form method="post" action="<?php print htmlspecialchars($_SERVER['PHP_SELF'])?>"> 
    <p> 
     Type your guess here: <input type="text" name="guess" /> 
     <input type="submit" value="submit" 
     <?php if (!$continue) { print("disabled=\"disabled\""); } ?> 
     /> 
    </p> 
    </form> 

    <h2> Your guess: </h2> 



</body> 
</html> 

我認爲使用谷歌發現JavaScript函數來獲取cookie的值,但沒有奏效。

function readCookie(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 change() 
    { 
     var color=readCookie(c); 
     color.innerHTML="You have chosen the " +color+" channel for guessing"; 
    } 

如何獲取cookie值?非常感謝你。

+2

我的意思是它是如此基本的和容易找到... https://www.w3schools.com/js/js_cookies.asp爲什麼來這裏直,而不是研究,谷歌搜索? – ProEvilz

+0

'readCookie(c);''你沒有設置'c'變量,除非它在更高的範圍內,並且你沒有顯示它(你應該) –

+0

在我的程序中,存儲了兩個cookie,顏色和maxNum。因此,我想知道我是否只能獲得顏色。 –

回答

0
<p> You have chosen the $_COOKIE[c] channel for guessing</p> 

你只是寫的文字。這裏沒有PHP代碼。

看你在這裏做什麼:

<form method="post" action="<?php print htmlspecialchars($_SERVER['PHP_SELF'])?>"> 

做到這一點!

<p> You have chosen the <?php print htmlspecialchars($_COOKIE['c']); ?> channel for guessing</p>