在 JavaScript 中访问 PHP 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4287357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access PHP variable in JavaScript
提问by sahil
Possible Duplicate:
How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>
可能的重复:
如何在 JavaScript 或 jQuery 中访问 PHP 变量而不是 <?php echo $variable ?>
Is there any way to get access to a PHP variable in JavaScript?
有没有办法在 JavaScript 中访问 PHP 变量?
I have a variable, $a
, in PHP and want to get its value in a JavaScript variable.
我$a
在 PHP 中有一个变量 ,并且想在 JavaScript 变量中获取它的值。
回答by metrobalderas
You can't, you'll have to do something like
你不能,你必须做类似的事情
<script type="text/javascript">
var php_var = "<?php echo $php_var; ?>";
</script>
You can also load it with AJAX
你也可以用 AJAX 加载它
rhino is right, the snippet lacks of a type for the sake of brevity.
rhino 是对的,为了简洁起见,该代码段缺少类型。
Also, note that if $php_var
has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.
另外,请注意,如果$php_var
有引号,它会破坏您的脚本。您应该使用addslashes、htmlentities 或自定义函数。
回答by rhino
metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:
Metrobalderas 是部分正确的。部分原因是 PHP 变量的值可能包含一些特殊字符,它们是 JavaScript 中的元字符。为避免此类问题,请使用以下代码:
<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>
回答by yitznewton
I'm not sure how necessary this is, and it adds a call to getElementById
, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:
我不确定这是多么必要,它添加了对 的调用getElementById
,但是如果您真的很想从代码中获取内联 JavaScript,则可以将其作为 HTML 属性传递,即:
<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>
And then in your JavaScript:
然后在你的 JavaScript 中:
var size_of_widget = document.getElementById("metadata-size-of-widget").title;