使用Javascript读取会话值

问题描述:

Is it possible to read a session value with Javascript?

For example, if I assigned a value into a session in PHP:

$_SESSION['msg'] = "ABC Message";

Is it possible to read $_SESSION['msg'] with Javascript?

是否可以使用Javascript读取会话值? p>

例如 ,如果我在PHP中为会话分配了一个值: p>

  $ _ SESSION ['msg'] =“ABC Message”; 
  code>  pre> \  n 
 

是否可以使用Javascript读取 $ _ SESSION ['msg'] code>? p> div>

$_SESSION is a server-side construct. You would need to store that variable in $_COOKIE to be able to access it client-side.

.. Or you can use ajax to retrive your server side session value into you client-side javascript.` (quick, dirty and untested example, using jQuery)

Javascript Side:

$.ajax({
      url: "test.php",
      cache: false,
      success: function(html){
        eval( html ); /// UGLY NASTY YOU MUST VALIDATE YOUR INPUTS... JUST AN EXAMPLE
      }
    });

PHP side test.php:

echo 'var myData = "'. $_SESSION['msg'].'"';

A very simple way is to generate the JavaScript with some PHP code:

<script type="text/javascript">
    <?php echo 'var msg = "'.json_encode($_SESSION['msg']).'";';
</script>

<script type="text/javascript">
var foo="<?php echo $_SESSION['user_id']; ?>";
alert(foo);
</script>

To make an even easier example of Luis Melgratti´s answer you can just return a json encoded value from PHP and use jQuery to parse it, like this:

Javascript:

$("#some_button")
    .click(function()
    {
        $.ajax(
        {
            url: "get_session.php",
            cache: false
        })
        .done(function(result)
        {
            var session_credentials = $.parseJSON(result);
            console.log(session_credentials);
        });
    });

PHP:

//get_session.php
<?php
    session_start();
    echo json_encode($_SESSION);
?>

I believe there are even more answers on a similar SO-thread here: how-to-access-php-session-variables-from-jquery-function-in-a-js-file

If this helps anyone, those examples returned null, so I just used:

<?php session_start();
   $msg = $_SESSION['msg'];
?>

<script>
   <?php echo "var msg = '" .$msg . "'"; ?>
</script>

May It Works :

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

getCookie('PHPSESSID');