js文件中的PHP变量 [英] PHP variable inside a js file
问题描述
如何将PHP变量的值放在Javascript变量中?
这就是我现在在js文件中的内容:
How do I put the value of a PHP variable inside a Javascript variable? This is what I have now in a js file:
test=<?php echo $country; ?>;
推荐答案
在传递之前不要忘记正确转义变量他们到JavaScript。使用 json_encode()
,因为它会转义并编码您的值以适合与JavaScript一起使用的方式:
Don't forget to properly escape your variables before passing them to JavaScript. Use json_encode()
for this, as it escapes and encodes your values in a way suitable for using with JavaScript:
test=<?php echo json_encode($country) ?>;
不要简单地发送未编码的变量,因为它可能会破坏事物,或者更糟糕的是,如果价值来自不受信任的来源,危及您的安全。
Never simply send the variable un-encoded, as it might break things, or, worse, if the value comes from untrusted sources, compromise your security.
此外,将您的文件重命名为 .php
而不是 .js
如果你想在其中插入动态PHP代码。
Also, rename your file to .php
instead of .js
if you want to be able to insert dynamic PHP code inside it.
这篇关于js文件中的PHP变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!