如何使用 JSON 作为 Javascript 的配置文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30031349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use JSON as config file with Javascript
提问by Stranger B.
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。
回答by charlietfl
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.
当然,这也创建了一个全局变量。
回答by Mephiztopheles
something like
就像是
var cfg = {};
$.ajax({
url: myUrl,
async: false,
success: function(data) {
cfg = JSON.parse(data);
}
});