将变量从PHP传递到JavaScript的有效方法

编程入门 行业动态 更新时间:2024-10-09 19:18:27
本文介绍了将变量从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的有效方法

本文发布于:2023-11-24 22:03:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627032.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   方法   PHP   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!