简体   繁体   English

Javascript检查是否定义了PHP变量

[英]Javascript check if PHP variable is defined or not

I can not find an answer to my problem and I am also not sure if this is possible or not. 我无法找到问题的答案,我也不确定这是否可行。

Is there any way to check if a PHP variable is defined or not with javascript? 有没有办法检查是否使用javascript定义了PHP变量?

This is an example: 这是一个例子:

var op = <?PHP echo json_encode($op); ?>;

if $op is not defined I got an error in javascript: 如果$op未定义我在javascript中出错:

Events:362 Uncaught SyntaxError: Unexpected token )

I understand this is normal because this variable does not exist in PHP. 我理解这是正常的,因为PHP中不存在这个变量。 But there is a way to avoid the error if the variable does not exist? 但是如果变量不存在,有一种方法可以避免错误吗?

Change: 更改:

var op = <?PHP echo json_encode($op); ?>;

To: 至:

var op = <?PHP echo (!empty($op) ? json_encode($op) : '""'); ?>;

PHP is executed on the server, before the response is even sent to the user. 在响应甚至发送给用户之前,PHP在服务器上执行。 Javascript is executed on the browser, once the user receives the response. 一旦用户收到响应,Javascript就会在浏览器上执行。 So "communicating" in the way you describe is not possible. 因此,以您描述的方式进行“沟通”是不可能的。 Just test in PHP if $op is empty, and output accordingly. 如果$op为空,只需在PHP中测试,并相应地输出。

你可以检查一下:

var op = <?php echo (isset($op) && $op) ? json_encode($op) : 'null'; ?>;

empty() is your best choice. empty()是你最好的选择。 http://php.net/manual/en/function.empty.php http://php.net/manual/en/function.empty.php

var op = <?= !empty($op) ? json_encode($op) : '""' ?>;

试试这样:

var op = <?= isset($op) ? json_encode($op) : "" ?>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM