本文介绍了将变量从PHP传递到JavaScript的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不时地从PHP传递一些变量到JS脚本。 现在我是这样做的:
From time to time I have to pass some variables from PHP to JS script. For now I did it like this:
var js-variable = "<?php echo $php-variable; ?>";但这是非常丑陋的,我不能隐藏我的JS脚本在.js文件,因为它由PHP解析。什么是最好的解决方案来处理这个?
But this is very ugly and I can't hide my JS script in .js file because it has to be parsed by PHP. What is the best solution to handle this?
推荐答案如果你不想使用PHP生成你的javascript(不介意你的网络服务器),使用AJAX来获取数据。
If you don't want to use PHP to generate your javascript (and don't mind the extra call to your webserver), use AJAX to fetch the data.
如果你确实想使用PHP,在输出之前总是用json_encode进行编码。
If you do want to use PHP, always encode with json_encode before outputting.
<script> var myvar = <?php echo json_encode($myVarValue); ?>; </script>更多推荐
将变量从PHP传递到JavaScript的有效方法
发布评论