我想知道如何从javascript文件中提取JSON数据。 javascript旨在用作配置文件,并包含一个带有JSON数据的变量。这类似于Magento 2中使用的require-config.js文件,仅供参考。它看起来像这样:
var chart=Highcharts.chart(id, {
chart: {
type: 'gauge',
alignTicks: false,
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false,
backgroundColor:'rgba(255, 255, 255, 0.0)'
},
exporting: { enabled: false },
title: {
text: ''
},
pane: {
startAngle: -150,
endAngle: 150,
background: {
from: 0,
to: partial+rejected,
backgroundColor: '#f55',
innerRadius: '85%',
outerRadius: '50%',
shape: 'arc',
},
},
yAxis: [{
lineWidth: 0,
min: 0,
max: parseInt(val),
tickInterval: 1,
tickPosition: 'outside',
minorTickColor: '#FF0000',
tickColor: '#FF0000',
tickWidth: 2,
tickLength: 10,
minorTickPosition: 'outside',
tickLength: 15,
minorTickLength: 5,
title:{text:'Total: '+val,style:{ color:"#333" }},
labels: {
distance: 25,
},
offset: 5,
endOnTick: false,
plotOptions: {
solidgauge: {
dataLabels: {
y: 5,
borderWidth: 0,
useHTML: true
}
}
},
plotBands: [{
from: 0,
to: delivered,
color: '#21A121',
thickness: '15%',
id: 'plot-band-1'
}]
}],
series: [{
name: 'Managed',
data: [{
id: 'deliver',
y: parseInt(total),
dial: {
backgroundColor:'#D9972E',
radius: '100%',
baseWidth: 10,
baseLength: '5%',
baseWidth: 15,
rearLength: '0%',
}
}],
dataLabels: {
formatter: function () {
var total = this.y;
return '<i class="ion-information-circled" title="RP: '+partial+'" style="color:#EEF007"></i><i class="ion-information-circled" title="RT: '+rejected+'" style="color:#F00707"></i>';
},
backgroundColor: {
linearGradient: {
x1: 10,
y1: 10,
x2: 10,
y2: 11
},
stops: [
[0, '#DDD'],
[1, '#FFF']
]
}
},
tooltip: {
valueSuffix: ' '
}
}]
});
答案 0 :(得分:1)
如果您正在访问此服务器端,则可以导出配置
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...
访问配置。
希望有所帮助。