简体   繁体   中英

JSON - proper way to decode string in JavaScript

I'm wondering what would be the best way to decode JSON string inside Javascript code.

I want my json string to be embeded inside my JS, like this:

var params = dojo.fromJson('<?=json_encode($this->params); ?>');

dojo.fromJson decodes my string and json_encode is a php function that encodes an object on the server side.

It seems that json encoder ignores ' chars and only converts " to \\". So when one of my variables inside $this->params contains a ' character there is a Javascript error.

For example:

var params = dojo.fromJson('{"id":"11","object_type":"Let's go"}');

What is the best way to approach this ?

Thanks for help.

Since you are producing the JSON yourself, you can trust it, so you don't need to treat it as JSON and can treat it as JS instead.

var params = <?=json_encode($this->params); ?>;

PHP's JSON encoder will escape </script> for you so you don't need to worry about terminating your script element with your data.

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