douhui1957 2015-02-24 17:15
浏览 52
已采纳

存储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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退