简体   繁体   English

在.JS文件中访问PHP变量

[英]Access PHP variable in .JS file

I'm trying to access a PHP variable in a JS file. 我正在尝试访问JS文件中的PHP变量。 The js file is appended at the end of the page. js文件被附加在页面的末尾。

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?). 现在,我只能想到2种可能的选择,但是两者似乎都有些棘手,我的问题是,这两种方法的优缺点是什么(或者有更好的方法吗?)。

Option 1: use inline scripts in my HTML file to set a variable. 选项1:在HTML文件中使用内联脚本来设置变量。 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. 选项2:使用HTML data-attributes将变量分配给HTML容器,然后使用jQuery检索它。 eg 例如

In HTML file: 在HTML文件中:

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

In JS file: 在JS文件中:

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

Any suggestions? 有什么建议么?

I'm pretty sure you should use json_encode for this. 我很确定您应该为此使用json_encode。 It returns the JSON representation of a php value. 它返回php值的JSON表示形式。 Something like this: 像这样:

In your php 在你的PHP中

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

In your javascript 在你的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. 这是将静态变量从PHP传递到JS的“最简单”方法-只需将其回显到变量或容器中即可,以后就可以将其提取出来。

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. 与将值嵌入HTML属性中相比,使用实际的JS变量的优点是可以将更复杂的数据类型放置在变量中,例如数组和对象。 With the data-attribute method, you're pretty much "stuck" with simple strings. 使用data-attribute方法,您几乎被简单的字符串“卡住了”。 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. 您的另一种选择是在页面加载后使用AJAX调用来传输数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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