How to assign JavaScript variable to PHP session variable?

◇◆丶佛笑我妖孽 提交于 2019-12-04 06:37:30

问题


Here's javascript code that i have

  var randomnum = 30;

and here's PHP code

<?php $_SESSION['numbertoguess'] = '<script>document.write(randomnum)</script>';?>

But this is not passing the value But when i am trying this code below, it works. It gives session variable that the value 'a sample thing'.

<?php $_SESSION['numbertoguess'] = 'a sample thing';?>

回答1:


Look at the following code. The PHP session is assigned to 30 from the Javascript value. however am not sure if this is good way for implementation.

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Html Page Title</title>
</head>

<body>

    <script>
        var randomnum = 30;
     </script>

    <?php $_SESSION['numbertoguess'] = '<script>document.write(randomnum)</script>';?>
    <?php echo $_SESSION['numbertoguess']; ?>
</body>
</html>



回答2:


You can't access Session directly in JavaScript.

You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById



来源:https://stackoverflow.com/questions/47522878/how-to-assign-javascript-variable-to-php-session-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!