且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在JavaScript中嵌入PHP代码?

更新时间:2023-01-30 22:01:26

如果您的整个JavaScript代码都由PHP处理,那么您可以这样做。如果您有单独的.js文件,并且您不希望PHP处理它们(例如,出于缓存原因),那么您只需在JavaScript中传递变量即可。例如,在index.php(或指定布局的任何地方),你可以这样做:

If your whole JavaScript code gets processed by PHP, then you can do it just like that. If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript. For example, in your index.php (or wherever you specify your layout), you'd do something like this:

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

然后您可以在JavaScript中使用 my_var 文件。此方法还允许您传递除简单整数值之外的其他值,因为json_encode()也正确处理数组,字符串等,将它们序列化为JavaScript可以使用的格式。

You could then use my_var in your JavaScript files. This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serializing them into a format that JavaScript can use.