简体   繁体   中英

Dealing with a non-existent variable in JavaScript

I am loading in a property from some PHP code using mustache as below:

PHP:

$data['foo'] = getFooAsJSON();

JavaScript:

var bar = <%&foo%>;

The issue here is that when <%&foo%> is sometimes non-existent and so the JS becomes:

var bar = ;

throwing syntax errors. I want to assign bar to be null as a fallback but given that <%&foo%> returns nothing, I'm not sure how to do this without invoking syntax errors.

Any ideas?

The name getFooAsJSON suggests that it returns JSON, which is a textual notation, and thus returns a string. That string cannot be blank and be valid JSON; it has to have something in it.

In the case where there's nothing to return, I'd suggest returning "null" , which is valid JSON and (therefore) also valid JavaScript. Then you'd end up with

var bar = null;

...in your JavaScript.

You can have a default argument for your PHP request.

PHP v5.3 and higher

$data['foo'] = getFooAsJSON() ?: 'null';

PHP v5.2 and lower

$jsonData = getFooAsJSON();

$data['foo'] = $jsonData ? $jsonData : 'null';

Credit to TJ Crowder for the note on valid JSON.

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