Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  23] [ 1]  / answers: 1 / hits: 64231  / 11 Years ago, fri, august 30, 2013, 12:00:00

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?


More From » php

 Answers
8

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 javascript json_encode will help you with this.


[#76010] Thursday, August 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ulysses

Total Points: 111
Total Questions: 118
Total Answers: 113

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
;