将PHP变量传递给JavaScript [英] Passing PHP variable into JavaScript
问题描述
我有一个PHP会话变量, $ _ SESSION ['user']
,在整个会话中都有效。在head部分,我包含了我的JavaScript文件, scripts.js
。
I've a PHP session variable, $_SESSION['user']
, alive throughout the session. In the head section, I've my JavaScript file included, scripts.js
.
如果我需要以下内容,如何将会话变量传递到JavaScript文件中。
How do I pass the session variable into the JavaScript file if I want something like the following.
$.("#btn').click (
function() {
alert('<?php echo $_SESSION['user']; ?>');
}
)
作为在JavaScript文件中无法识别<?php?>
,上面的代码不起作用。所以我要自己输入PHP文件,但是如何保留它JavaScript文件?
As the <?php ?>
isn't recognized in the JavaScript file, the code above doesn't work. So I've to put in the PHP file itself, but how do I keep it in the JavaScript file?
推荐答案
在PHP文件中,您可以将用户设置为全局变量:
In your PHP file you could set your user as a global varibale:
<script type="text/javascript">
var ptamzzNamespace = {
sessionUser : '<?php echo $_SESSION['user']; ?>'
}
</script>
在包含外部JavaScript代码之前包含此内容。
Include this before including your external JavaScript code.
然后在您的JavaScript文件中,您可以使用它:
Then in your JavaScript file you can use it:
$.("#btn').click (
function() {
alert(ptamzzNamespace.sessionUser);
}
)
此外:
如果你不确定你的会话varibale是否可以自己包含引号,你可以使用 addslashes()
来解决这个问题:
<?php echo addslashes($ _ SESSION ['user']); ?>
即使这可能产生你不想显示的东西(因为它产生带有斜杠的字符串),它将有助于你的代码不会失败。 (感谢Artefacto)
<?php echo addslashes($_SESSION['user']); ?>
even if this will maybe produce something you don't really want to display (because it produces a string with slashes) it will help that your code will not fail. (Thanks to Artefacto)
这会是你的选择吗?
这篇关于将PHP变量传递给JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!