Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JSON as config file with Javascript

I'm looking for a way where I can use a JSON as a config file,

My JSON config file looks like :

{
'Lang' : 'EN',
'URL' : '/over/dose/app'
}

and I want to get the URL and Lang in the html file using javascript or jQuery. I don't wanna use an asynchronous method like $.getJson.

I want to get the Url and language from JSON file something like :

var url = myjson.URL;

so I can use the var later in so many different functions.

like image 349
Stranger B. Avatar asked May 04 '15 13:05

Stranger B.


1 Answers

If you don't want to use an asynchronous call you can always assign a variable to the config object and put the file in the src of a script tag

var appConfig={
    'Lang' : 'EN',
    'URL' : '/over/dose/app'
}

.

<script src="/path/to/config.js"></script>
<script> alert(appConfig.URL);</script>

Advantage is immediate loading. Possible disadvantage is it isn't a json file any more, it is regular javascript file in case you are writing to it from server code.

Of course this also creates a global variable.

like image 193
charlietfl Avatar answered Sep 24 '22 16:09

charlietfl