如何在AJAX回调中编写完整Highcharts配置,实现EJS数据转JSON生成动态图表
解决方案
方案1:直接通过EJS注入JSON数据(无需AJAX)
原有模板循环渲染数组的方式容易出现多余逗号、特殊字符转义错误问题,直接用JSON.stringify注入更稳妥,修改series部分即可:
series: [{ name: 'Expected', // <%- 是输出原始内容,不会转义引号,可生成合法JS数组 data: <%- JSON.stringify(expected_data) %>.sort() }, { name: 'Actual', data: <%- JSON.stringify(actual_data) %>.sort() }]
你用到的customRange/timezone/chartTitle/subTitle这些变量也可以用同样方式注入。
方案2:完整AJAX异步拉取+回调生成图表
后端Node.js(Express示例)接口代码
先新增一个接口返回所有图表所需数据:
// 接口路由示例,路径自定义为 /api/chart-data app.get('/api/chart-data', async (req, res) => { // 复用你原来渲染EJS时的业务逻辑,获取所有配置参数和数据 const expected_data = await getExpectedData() // 替换为你的数据获取逻辑 const actual_data = await getActualData() res.json({ customRange: 1, // 替换为你的自定义配置值 timezone: -480, // 东八区对应timezoneOffset为-480,按需修改 chartTitle: "未平仓合约数据", subTitle: "预期值与实际值对比", expected_data, actual_data }) })
前端完整代码
所有Highcharts初始化逻辑全部放在AJAX回调中:
<script src="https://code.highcharts.com/stock/highstock.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> <script src="https://code.highcharts.com/modules/export-data.js"></script> <script src="https://code.highcharts.com/modules/accessibility.js"></script> <script src="https://code.highcharts.com/stock/modules/drag-panes.js"></script> <link rel="stylesheet" type="text/css" href="/public/oi chart.css"> </head> <figure class="highcharts-figure"> <div id="container"></div> </figure> <script type="text/javascript"> const xhr = new XMLHttpRequest() xhr.open('GET', '/api/chart-data', true) xhr.onload = function () { if (xhr.status >= 200 && xhr.status < 300) { const config = JSON.parse(xhr.responseText) // 图表初始化逻辑全写在回调内 Highcharts.stockChart('container', { chart: { height: (1 / 2 * 100) + '%' // 1:2比例 }, rangeSelector: { enabled: true, selected: config.customRange, buttons: [{ type: 'day', count: 1, text: '1D' }, { type: 'week', count: 1, text: '1W' }, { type: 'week', count: 2, text: '2W' }, { type: 'month', count: 1, text: '1M' }, { type: 'all', text: 'All' }] }, time: { timezoneOffset: config.timezone }, title: { text: config.chartTitle }, subtitle: { text: config.subTitle }, yAxis: { offset: 60, title: { text: 'Open Interest' }, resize: { enabled: true } }, xAxis: { type: 'datetime' }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, plotOptions: { series: { marker: { enabled: false }, label: { connectorAllowed: false } } }, series: [{ name: 'Expected', data: config.expected_data.sort() }, { name: 'Actual', data: config.actual_data.sort() }], responsive: { rules: [{ condition: { maxWidth: 500 }, chartOptions: { legend: { layout: 'horizontal', align: 'center', verticalAlign: 'bottom' } } }] } }); } } xhr.send() </script> </html>
注意事项
- 不需要动态刷新数据的场景下优先使用方案1,实现更简单
- 方案2完全不需要EJS注入任何变量,所有配置和数据都通过接口异步获取,后续要做图表动态刷新直接重新调用接口重新初始化图表即可
内容的提问来源于stack exchange,提问作者yen
相关产品推荐
相关产品推荐

