在Javascript文件中插入PHP变量值

在Javascript文件中插入PHP变量值

问题描述:

我有一个JavaScript文件,它有一个硬编码的BASEURL变量,然后该值被文件中的其他函数使用。
我想要动态设置这个url值,这样我就不需要为不同的安装手动更改它。是否可以将PHP变量值插入JavaScript文件?

I have a JavaScript file which has a hard coded BASEURL variable, this value is then used by other functions in the file. I would like for this url value to be set dynamically so that I don't need to manually change it for different installs. Is it possible to insert a PHP variable value into a JavaScript file?

而不是尝试将PHP混合到javascript文件中,这里是我在HTML模板中的操作:

Rather than try to mix PHP into javascript files, here's what I do in the HTML template:

<head>
    <script>
        var BASEURL = "<?php echo base_url(); ?>";
    </script>
    <script src="/path/to/my_script1.js"></script>
    <script src="/path/to/my_script2.js"></script>
</head>

这将设置变量并允许所有嵌入式脚本访问它。 base_url()将替换为用于通过PHP获取基本URL的任何方法。

This sets the variable and allows all your embedded scripts to access it. base_url() would be replaced by whatever method you use to fetch the base url with PHP.