douhui1957
douhui1957
2015-02-24 17:15
浏览 47

存储PHP变量以便稍后在同一脚本中使用

I know that PHP happens server-side and javascript is executed once the page loads in the browser. I'm trying to figure out how to save a variable in PHP so that it can be used in a javascript function later on. Here are the bits of my code where I'm trying to do that.

This all happens in the same index.php script:

    <? 
    // If session token exists, set javascript variable 
    if($_SESSION['token'] != null) 
    { 
        // Store session token as a variable 
        $sessionToken = $_SESSION['token']; 
    } 
    ?>

    <script>
      // Turn that PHP variable into a javascript variable
      var sessionToken = '<? echo $sessionToken; ?>';
    </script>

    <script>
      // This function works. It sends a string to the Unity web player
      // I'm trying to call it using a PHP variable as a parameter
      function SessionTokenToUnity($token) {
        // Send message to unity web player from browser
        u.getUnity().SendMessage("Settings", "MyFunction", $token);
      }
    </script>

    <script>
      // Call function with sessionToken which was set by PHP earlier as a parameter
      SessionTokenToUnity(sessionToken);
    </script>

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwei3712
    dongwei3712 2015-02-24 17:18
    已采纳

    You need to session_start(); at beggining of your file to be able to use $_SESSION.

    And you have some sintax errors like:

    if($_SESSION[ 'token'] !=n ull)

    $sessionToken=$ _SESSION[ 'token'];

    it should be

    if($_SESSION['token'] !=null)

    $sessionToken=$_SESSION['token'];

    Edit: And you should use isset($_SESSION['token']) like ByteHamster told it.

    点赞 评论

相关推荐