I'm trying to create a common constants file to share between php and javascript, using JSON to store the constants. But I'm wondering why pass the JSON from PHP to javascript using json_encode()
over echoing the json declaration.
Let's say I have the PHP JSON
<?php
$json_obj = '{"const1": "val",
"const2": "val2"
}';
?>
Googling, it seems the typical way of passing back to javascript is using
<?php echo json_encode($json_obj); ?>
Then I believe I would have to use something like $.getScript()
to read the php file to get $json_obj
and then use parseJSON()
to make it useable in javascript.
But why not instead
<?php echo 'var json = '.$json_obj; ?>
This way all you have to do is load the script directly and you have the json ready to use directly.
Is there a particular reason why it is more favorable to use json_encode()
then simply echoing the declaration to javascript?
In your case
$json_obj
is already a string. So it is not necessary. But if you have an array you want to pass to javascriptjson_encode
will help you with this.