最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get for jQuery ID from session PHP? - Stack Overflow

programmeradmin1浏览0评论

I have in session PHP:

$_SESSION['id'] = 2;

how can i get this for jQuery?

<script>
   var sessionid = ??? ;
   alert(sessionid);
</script>

I have in session PHP:

$_SESSION['id'] = 2;

how can i get this for jQuery?

<script>
   var sessionid = ??? ;
   alert(sessionid);
</script>
Share Improve this question asked Jan 9, 2012 at 11:53 Mark FondyMark Fondy 3,9338 gold badges26 silver badges26 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5
<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>
发布评论

评论列表(0)

  1. 暂无评论