我想知道如何从 javascript 文件中提取 JSON 数据。javascript 旨在用作配置文件,其中包含一个带有 JSON 数据的变量。这类似于 Magento 2 中使用的 require-config.js 文件,仅供参考。它看起来像这样:
var config = {
fieldsets : [
{
title : 'Quote Essentials',
description : 'Some',
fields : [
{
label : 'What type of project is this for?',
required : true,
class : '',
type : 'input',
inputType : 'text',
hint : 'For example: company uniforms, clothing line, school events, etc.',
id : ''
},
{
label : 'How many total items do you need?',
required : true,
class : '',
type : 'input',
inputType : 'text',
hint : 'Please note: the minimum order size is 24 pieces.',
id : ''
},
...
如果您正在访问此服务器端,则可以导出配置
module.exports = {
fieldset: [ ... ]
}
并且require
它
const config = require('./config.js');
如果您尝试在客户端访问它,只需将配置脚本放在访问它的脚本之前,您就可以像访问任何其他对象一样访问它:
config.fieldset...
这样做的一个问题是您config
直接将变量添加到window
其中,这样做可能会覆盖现有config
变量。可能不太可能,但缓解这种情况的一种方法是为您的代码提供一个命名空间,这样您就不会污染全局命名空间并且代码变得更加模块化。WRT 到您的配置文件,您的命名空间技术可能像这样工作:
// Semi-colon to prevent minify issues
// Pass `window` into the immediately-invoked function expression
// as an argument
;(function (window) {
// config is local to this function and can't leak
var config = { ... };
// If the `app` variable isn't available, create it
window.app = window.app || {};
// Add config to the app namespace
window.app.config = config;
})();
您可以执行与其余代码类似的操作。
您将使用app.config.fieldset...
.
希望有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句