javascript - 在 php 中显示 cookie

标签 javascript php cookies

我想在 php 中显示 javascript 变量,我使用 cookies 来做到这一点,但我运行这个会出现一些错误。这就是错误

Notice: Use of undefined constant latitude - assumed 'latitude' in C:\wamp\www\varCoo.php on line 16

Notice: Undefined index: latitude in C:\wamp\www\varCoo.php on line 16 

Notice: Use of undefined constant longitude - assumed 'longitude' in C:\wamp\www\varCoo.php on line 17

Notice: Undefined index: longitude in C:\wamp\www\varCoo.php on line 17

我的代码有什么问题吗?

<!DOCTYPE html>
<head>
<title>Untitled Document</title>
</head>

<body>
<script>
    var x = -40;
    var y = 72;
    document.cookie = latitude + "=" + x;
    document.cookie = longitude + "=" + y;
</script>
<?php
    echo $_COOKIE[latitude];
    echo $_COOKIE[longitude];
?>
</body>
</html>

最佳答案

可以这样写

  <script>
    var x = -40;
    var y = 72;
    document.cookie = 'latitude' + "=" + x;
    document.cookie = 'longitude' + "=" + y;
</script>

<?php
if(isset($_COOKIE['latitude']) && isset($_COOKIE['longitude']))
  {  
     echo $_COOKIE['latitude'];
     echo $_COOKIE['longitude'];
  }else{
    ?>
    <script type="text/javascript">
    document.body.innerHTML = x +'<br>'+y; // or in some element as you like
    </script>
    <?php
}
?>
</body>

关于javascript - 在 php 中显示 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32425218/

相关文章:

php - 我丢失了 WordPress 管理员密码

php - 从 php 执行 C 代码

javascript - 根据页面的不同,在 WordPress 中显示不同的内容(如 is_home,但对于其他页面)

javascript - 在 Javascript 中设置 Cookie 在值存在时返回未定义

html - YouTube 在哪里存储播放器速度首选项?

javascript - VueJs - 动画数字变化

javascript - jquery Select2 防止在 ajax 响应中选择

javascript - Pixi.js 页面刷新不断加速

javascript - 为什么这个变量未定义?

javascript - 将 JavaScript 函数存储在 cookie 中?