PHP 中的布尔变量值到 javascript 实现
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5517748/
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
boolean variable values in PHP to javascript implementation
提问by julio
I've run into an odd issue in a PHP script that I'm writing-- I'm sure there's an easy answer but I'm not seeing it.
我在编写的 PHP 脚本中遇到了一个奇怪的问题——我确定有一个简单的答案,但我没有看到。
I'm pulling some vars from a DB using PHP, then passing those values into a Javascript that is getting built dynamically in PHP. Something like this:
我正在使用 PHP 从数据库中提取一些变量,然后将这些值传递到在 PHP 中动态构建的 Javascript 中。像这样的东西:
$myvar = (bool) $db_return->myvar;
$js = "<script type=text/javascript>
var myvar = " . $myvar . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";
The problem is that if the boolean value in the DB for "myvar" is false
, then the instance of myvar in the $js is null, not false
, and this is breaking the script.
问题是,如果数据库中“myvar”的布尔值为false
,则 $js 中的 myvar 实例为 null,而不是false
,这会破坏脚本。
Is there a way to properly pass the value false
into the myvar variable?
有没有办法将值正确传递false
到 myvar 变量中?
Thanks!
谢谢!
回答by Marc B
use json_encode()
. It'll convert from native PHP types to native Javascript types:
使用json_encode()
. 它将从原生 PHP 类型转换为原生 Javascript 类型:
var myvar = <?php echo json_encode($my_var); ?>;
and will also take care of any escaping necessary to turn that into valid javascript.
并且还将处理将其转换为有效 javascript 所需的任何转义。
回答by Wh1T3h4Ck5
This is the simplest solution:
这是最简单的解决方案:
Just use var_export($myvar)instead of $myvarin $js;
只需在 $js 中使用var_export($myvar)而不是$myvar;
$js = "<script type=text/javascript>
var myvar = " . var_export($myvar) . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";
Note: var_export()is compatible with PHP 4.2.0+
注意:var_export()兼容 PHP 4.2.0+
回答by Hamish
$js = "<script type=text/javascript>
var myvar = " . ($myvar ? 'true' : 'false') . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";