如何使用JSON作为配置文件使用Javascript [英] How to use JSON as config file with Javascript

查看:355
本文介绍了如何使用JSON作为配置文件使用Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

My JSON config file looks like :

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

我希望得到使用javascript或jQuery在html文件中的URL和Lang。
我不想使用像 $。getJson 这样的异步方法。

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.

我想得到来自JSON文件的Url和语言类似于:

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

var url = myjson.URL;

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

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

推荐答案

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

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>

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

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.

这篇关于如何使用JSON作为配置文件使用Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆