js文件中的PHP变量 [英] PHP variable inside a js file

查看:229
本文介绍了js文件中的PHP变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在PHP和Javascript之间传输数组的最佳方法

如何将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆