将服务器端变量传递给PHP中的Javascript [重复]

This question already has an answer here:

What is the best way to pass a server-side PHP variable to Javascript?

To simplify the problem assume that we have a variable in PHP ($phpVar) and we want to assign its value to a Javascript variable (jsVar)

Javascript files are loaded in html - they are not created dynamic!

Some food for thought:

1. Print with PHP before loading Javascript files:

    <script language="javascript" type="text/javascript">
       var jsVar= <?php echo $phpVar?>;
    </script>

2. Store in DOM (in hidden elements)

a. in PHP:

    <span data-name="phpVar" data-value="<?php echo $phpVar?>"></span>

b. Read in Javascript files (assuming jQuery available):

    var jsVar= $('span[data-name="phpVar"]').attr('data-value');

3. Ask it with AJAX after page has loaded

Obviosly not the best solution. Doesn't fit to all scenarios and requires an additional request...

In conclusion:

  • They both seem ugly to me... Is there a better approach?
  • Is there any frameworks that can handle this dependecies? Please keep server reconfiguration minimal.
</div>

It depends on the situation, but in common, predominantly to use first case. But don't forget about quotes if you pass a string:

<script language="javascript" type="text/javascript">
    var jsVar = '<?php echo $phpVar?>';
</script>

The best approach would be providing an "internal API" requested via AJAX from client side. Doing this way you can keep your sides separated.

After this, the fastest way is printing in a shared file the values you want to share (as you wrote in your question).

As a last note: if you carry on with the second way I would suggest you

json_encode()

as a really helpful method to pass arrays and objects from php to javascript.

So if you have your php array:

$array = array( "a" => 1, "b" => 2 );

<script language="javascript" type="text/javascript">
    var js_array= <?php echo json_encode( $array ) ; ?>;
</script>