如何从项目目录中读取javascript中的属性文件?
我正在构建Chrome打包应用程序。 如果配置文件在资源目录中并且在启动时想要通过Javascript读取它,我想放置脚本配置。
例如
- 项目
- 网页内容
- 的index.html
- 的manifest.json
- main.js
- 资源
- config.properties
- 网页内容
在这里,我希望main.js在开头加载config.properties文件并获取键值对。
有没有人做过这样的事情?
根据sowbug的答案,有一种超级简单的方法可以做到这一点,但不需要任何XHR或文件读取。
步骤1.创建资源/ config.js,如下所示:
gOptions = { // This can have nested stuff, arrays, etc. color: 'red', size: 'big', enabled: true, count: 5 }
第2步。在index.html中包含此文件:
...
第3步。直接从main.js(或任何地方)访问您的选项:
... if (gOptions.enabled) { for (var i = 0; i < gOptions.count; i++) { console.log(gOptions.color); } } ...
您可以使用messageResource.js ,这是我创建的一个简单的javascript库,用于加载属性文件。
1)在index.html中包含messageResource.js。
2)您可以使用以下代码从main.js获取config.properties的键值对。
// initialize messageResource.js messageResource.init({ // path to directory containing config.properties filePath : 'resource' }); // load config.properties file messageResource.load('config', function(){ // load file callback // get value corresponding to a key from config.properties var value = messageResource.get('key', 'config'); });
将文件结构化为JSON。 使用File API或XHR将其读入字符串。 然后是JSON.parse(字符串)。
- 通过XHR在Chrome打包应用中加载本地内容
- http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
使用JSF非常简单,但每次需要从JavaScript读取新参数时,都必须修改HTML文件。 项目目录中的属性文件( config.properties )具有以下参数作为键值对。
parameter.key=parameter.value
属性文件名在faces-config.xml中配置
com.example.project.properties.config configuration
因此,您可以在HTML文件中的隐藏输入中使用属性值。
并且从JavaScript函数中,使用以下行来读取参数值。
var parameter_value = document.getElementById("parameter_key").value;
祝您愉快..!!!