如何使用JSON作为配置文件使用Javascript

时间:2022-11-19 01:53:51

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

我正在寻找一种可以使用JSON作为配置文件的方法,

My JSON config file looks like :

我的JSON配置文件如下所示:

{
'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.

我想使用javascript或jQuery获取html文件中的URL和Lang。我不想使用像$ .getJson这样的异步方法。

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

我想从JSON文件中获取Url和语言:

var url = myjson.URL;

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

所以我可以在很多不同的函数中使用var。

2 个解决方案

#1


14  

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

如果您不想使用异步调用,您始终可以将一个变量分配给配置对象,并将该文件放在脚本标记的src中

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

优点是立即加载。可能的缺点是它不再是json文件,它是常规的javascript文件,以防你从服务器代码写入它

Of course this also creates a global variable.

当然,这也会创建一个全局变量。

#2


0  

something like

就像是

var cfg = {};
$.ajax({
  url: myUrl,
  async: false,
  success: function(data) {
    cfg = JSON.parse(data);
  }
});

#1


14  

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

如果您不想使用异步调用,您始终可以将一个变量分配给配置对象,并将该文件放在脚本标记的src中

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

优点是立即加载。可能的缺点是它不再是json文件,它是常规的javascript文件,以防你从服务器代码写入它

Of course this also creates a global variable.

当然,这也会创建一个全局变量。

#2


0  

something like

就像是

var cfg = {};
$.ajax({
  url: myUrl,
  async: false,
  success: function(data) {
    cfg = JSON.parse(data);
  }
});