Pass JSON from php to javascript

I want to localize my webapp. Since localization through javascript is not recommended, I thought using php would be an alternative.

So, with php, I read the messages.json file, which stores all the localization data.

 $json = file_get_contents("_locales/en/messages.json"); 

In the header of my webapp, I generate javascript with php according to the user's browser language.

 echo "var localeObj = " . $json . ";"; 

So this is just a var that contains all the data from the m essages.json file, which looks like this:

 { "extTitle": { "message": "Test1" }, "extName":{ "message": "Test2" } } 

Now I want to have access to every element from json, like

 var title = getItem("extTitle"); 

and it returns Test1 . Any idea how to do this?

I am not very familiar with json, but if I just warn localeObj , it gives me just [object Object].

+4
source share
4 answers
 var getItem = function(item) { return localObj[item].message; }; 

You can also encapsulate your i18n strings ...

 (function() { var localObj = { ... }; window.getItem = function(item) { return localObj[item].message; }; })(); 

Thus, no other variables can compress your localObj .

+4
source

To access the properties of a javascript object, the array [] syntax or dot syntax is used . .

Example:

 localeObj["extTitle"]; localeObj.extTitle; 

I would recommend reading something like this to learn more about JSON.

+1
source

You can initialize a javascript variable like this.

 var json = eval(<? echo $json ?>); alert(json.extTitle.message+ ' '+json.extName.message); 
+1
source

Inside messages.php :

 <?php header('Content-type:application/javascript'); $messages = array( "yes"=>"hai", "no"=>"iie" ); $messages = json_encode($messages); echo "window.messages = $messages"; ?> 

Inside index.html :

 <html> <body> <script type="text/javascript" src="messages.php"></script> <script type="text/javascript"> console.log(window.messages) </script> </body> </html> 

As long as you tell the browser to interpret the php file as a javascript file, you can drive off whatever you want.

0
source

Source: https://habr.com/ru/post/1341091/


All Articles