简体   繁体   中英

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?

This is an example:

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

if $op is not defined I got an error in javascript:

Events:362 Uncaught SyntaxError: Unexpected token )

I understand this is normal because this variable does not exist in 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. Javascript is executed on the browser, once the user receives the response. So "communicating" in the way you describe is not possible. Just test in PHP if $op is empty, and output accordingly.

你可以检查一下:

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

empty() is your best choice. http://php.net/manual/en/function.empty.php

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

试试这样:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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