简体   繁体   English

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

[英]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, 我正在寻找一种可以使用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. 我想使用javascript或jQuery获取html文件中的URL和Lang。 I don't wanna use an asynchronous method like $.getJson . 我不想使用像$.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。

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. 当然,这也会创建一个全局变量。

something like 就像是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM