PHP中的布尔变量值到javascript的实现 [英] boolean variable values in PHP to javascript implementation

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

问题描述

我在编写PHP脚本时遇到了一个奇怪的问题-我敢肯定有一个简单的答案,但我没有看到它.

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从数据库中提取一些变量,然后将这些值传递到在PHP中动态构建的Javascript中.像这样:

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:

$myvar = (bool) $db_return->myvar;

$js = "<script type=text/javascript>
        var myvar = " . $myvar . ";
        var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
       </script>";

问题在于,如果数据库中"myvar"的布尔值是false,则$ js中myvar的实例为null,而不是false,这将破坏脚本.

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.

是否可以将值false正确传递到myvar变量中?

Is there a way to properly pass the value false into the myvar variable?

谢谢!

推荐答案

使用json_encode().它将从本地PHP类型转换为本地Javascript类型:

use json_encode(). It'll convert from native PHP types to native Javascript types:

var myvar = <?php echo json_encode($my_var); ?>;

,并且还将处理将其转换为有效javascript所需的所有转义操作.

and will also take care of any escaping necessary to turn that into valid javascript.

这篇关于PHP中的布尔变量值到javascript的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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