将 php 变量值传递给 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10437703/
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
pass php variable value to javascript
提问by cclerv
Im trying to pass the value of a php variable into javascript but i just cant get it to work. Am I doing anything wrong? Below is the line of code I'm working with.
我试图将一个 php 变量的值传递给 javascript,但我无法让它工作。我做错了什么吗?下面是我正在使用的代码行。
var dist = parseInt("<?php echo json_encode($distance); ?>");
回答by Sebastian Breit
$distance is an integer? why don't you just write
$distance 是一个整数?你为什么不写
var dist = <?php echo $distance; ?>
回答by Lucas Holt
If the value in $distanceis just an integer, you don't need the json_encode call. You can just do a php echo of $distance.
如果$distance 中的值只是一个整数,则不需要 json_encode 调用。你可以做一个$distance的php echo 。
Something like
就像是
var dist = <?php echo $distance; ?>;
回答by goat
if you right click > view html source in your web browser, you would see for yourself that you have an extra set of quotes.
如果您右键单击 > 在 Web 浏览器中查看 html 源代码,您会亲眼看到您有一组额外的引号。
And, good for you for using json_encode() to output it as a string. That's an excellent way to safely output a value to javascript. although, if its an integer, theres no need here.
而且,使用 json_encode() 将其作为字符串输出对您很有好处。这是将值安全地输出到 javascript 的极好方法。虽然,如果它是一个整数,这里就不需要了。