开发者

What's the best way to pass a PHP variable to Javascript? [duplicate]

开发者 https://www.devze.com 2022-12-29 06:48 出处:网络
This question already has answers here: How do I pass variables and da开发者_如何学Cta from PHP to JavaScript?
This question already has answers here: How do I pass variables and da开发者_如何学Cta from PHP to JavaScript? (19 answers) Closed 8 years ago.

I currently echo certain variables in hidden input fields and read them out with Javascript whenever I need them.

Me and a colleague are now thinking of generating an extra Javascript file with PHP which only contains all variables for Javascript. This way the variables already exist and there is no extra code in the HTML.

What are good ways to pass variables from PHP to Javascript? And how does our solution sound?


General Data Passing

A commonly used exchange format for JavaScript is JSON, using json_encode. A PHP file like this:

<?php
    $data = array("test" => "var", "intvalue" => 1);
    echo json_encode($data);
?>

then returns a JavaScript object literal like this:

{
    "test" : "var",
    "intvalue" : 1
}

You can directly echo it into a JavaScript variable on your page, e.g.:

var data = <?php echo json_encode($data)?>;

...or request it via Ajax (e.g. using jQuery's getJSON).

Outputting to attributes on tags

If you just need to output a string to an attribute on a tag, use htmlspecialchars. Assuming a variable:

<?php
$nifty = "I'm the nifty attribute value with both \"double\" and 'single' quotes in it.";
?>

...you can output it like this:

<div data-nifty-attr="<?php echo htmlspecialchars($nifty)?>">...</div>

...or if you use short tags:

<div data-nifty-attr="<?= htmlspecialchars($nifty)?>">...</div>


<?php
  $my_php_var = array(..... big, complex structure.....);
?>
<script type="text/javascript">
  my_js_var = <?=json_encode ($my_php_var)?>;
</script>


I use to echo them all together at the head of the HTML. Seems clean enough for my needs :)


There are 3 ways you could do it:

  • Echo them directly into the javascript source: <?echo "var user = '$user';";?>. Works, but it's messy.
  • Pass them in via an ajax request. This is the closest you can come to native variable passing, but the downside is it takes an extra HTTP request.
  • What you're doing, which is passing them by generating hidden form fields and then reading them.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号