简体   繁体   中英

Access PHP variable in .JS file

I'm trying to access a PHP variable in a JS file. The js file is appended at the end of the page.

Now I can only think of 2 possible options, but both seem kind of hacky and my question is, what are the pros & cons of both approaches (or is there a better way?).

Option 1: use inline scripts in my HTML file to set a variable. eg

<body>
    <script type="text/javascript">
        var link = "<?= $var ?>";
    </script>
</body>

Option 2: use HTML data-attributes to assign the variable to an HTML container, and later retrieve it with jQuery. eg

In HTML file:

<body>
    <div id="container" data-ajaxVar="<?= $var ?>">
        Random html
    </div>
</body>

In JS file:

var link = $("#container").data("ajaxVar");

Any suggestions?

I'm pretty sure you should use json_encode for this. It returns the JSON representation of a php value. Something like this:

In your php

$n1 = array();
echo json_encode($n1);

In your javascript

  var link = $("#container").data(data.n1);

Can't do more, I'm on my phone, this was a pain. Some documentation here.

Both of your options are essentially the same. It's the "easiest" way to pass a static variable from PHP to JS - just echo it out into a variable or into a container that you can extract it from later.

The advantage of using an actual JS variable as opposed to embedding the value in an HTML attribute is that you can place more complex data types in the variable like arrays and objects. With the data-attribute method, you're pretty much "stuck" with simple strings. These can be converted later but it's just another step that you'll have to take.

Your other option would be to transfer the data using an AJAX call after the page has loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM