Set JavaScript variable from PHP

后端 未结 2 1725
忘掉有多难
忘掉有多难 2020-12-06 14:03

How I can set the JavaScript variable strUser from PHP?

I am using the following code:



        
相关标签:
2条回答
  • 2020-12-06 14:23

    If you want to set the variable when the page loads, you could use something like this in the PHP code:

    <script type="text/javascript">var strUser = <?php echo json_encode($someVariable); ?>;</script>
    

    Just make sure to remove the later variable declaration from the JavaScript.

    If you want to set the variable after the page loads, you'll have to use an AJAX call to ge the value from the server.

    0 讨论(0)
  • 2020-12-06 14:27

    Use Cookie in your javascript

    <script type="text/javascript">
        document.cookie = "cookieName=cookieValue";
    </script>
    

    in your php

    <?php 
       $phpVar =  $_COOKIE['cookieName'];
    
       echo $phpVar;
    ?>
    
    0 讨论(0)
提交回复
热议问题