【问题标题】:How to print out the cookie value in HTML?如何在 HTML 中打印出 cookie 值?
【发布时间】:2017-10-04 17:15:22
【问题描述】:

我正在开发一个猜数字的网站。网站概览如下图所示: enter image description here

在 setCookiesA.php 中,存储了两个名为 c(color) 和 maxNum(最大猜测次数) 的 cookie。存储 cookie 后,播放器将被重定向到 GuessingA.php。代码如下:

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

进入GuessingA.php后,应该在“You have selected the ??? channel for guessing”这句话中打印出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>

我考虑过使用 google 中的 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值?非常感谢。

【问题讨论】:

  • 我的意思是它很基础而且很容易找到...w3schools.com/js/js_cookies.asp 为什么直接来这里而不是研究、谷歌搜索?
  • readCookie(c); 你没有设置c 变量,除非它在更高的范围内并且你没有显示它(你应该这样做)
  • 在我的程序中,存储了两个cookie,颜色和maxNum。因此,我想知道我是否只能获得颜色。

标签: javascript php html


【解决方案1】:
<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多