简体   繁体   中英

How to get for jQuery ID from session PHP?

I have in session PHP:

$_SESSION['id'] = 2;

how can i get this for jQuery?

<script>
   var sessionid = ??? ;
   alert(sessionid);
</script>
<script>
   var sessionid = "<?php echo $_SESSION['id'] ?>" ;
   alert(sessionid);
</script>

don't forget to call session_start();

You could set it as the ID of an element (like the HTML element) if you want to access it from a script:

<html id="<?php echo $_SESSION['id']; ?>">

In the external script:

var sessionid = $('html').attr('id');
alert (sessionid);

This has the added benefit of being able to be read by an external script.

EDIT:

You would need to set the session before you output anything, so the full code would be something like:

<?php
  session_start();
  if (!isset($_SESSION['id']))
    $_SESSION['id'] = 'session1';
?><html id="<?php echo $_SESSION['id']?>">
  <head>
    <title>SESSION ID TEST</title>
    <script>
      $(function(){
        var sessionid = $('html').attr('id');
        alert (sessionid);
      })
    </script>
  </head>
</html>

javascript executes on the client, which has no knowledge of a session id natively. You'll have to echo out the session id to assign the value to a javascript variable:

var sessionid = "<? echo $_SESSION['id']?>";

How about..

<script>
 var sessionid = "<? echo $_SESSION['id']?>";
 alert(sessionid);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM