首页 > 解决方案 > echarts:从 URL 获取数据

问题描述

我正在其演示页面上测试 Echarts 功能:https ://ecomfe.github.io/echarts-examples/public/editor.html?c=line-simple

现在我希望该图表显示从 URL 收集的数据。该 URL 返回“[820, 932, 901, 934, 1290, 1330, 1320]”。

演示代码(正在运行)是:

option = {
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: 'line'
    }]
};

我的代码(不起作用)是:

option = {
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        url: 'https://www.myurl.com/echartstest.php',
        type: 'line'
    }]
};  

当我在代码中使用我的 URL 时,没有返回错误,但没有显示图表。

如有必要,我可以在我的项目中使用 AJAX。

标签: phpmysqlajaxecharts

解决方案


var dataArr = [];
     $.get('https://www.myurl.com/echartstest.php', {}, function(response) {
            dataArr = JSON.parse(response);
              initEchart();
            });
// make sure dataArr should be in array like [1,2,3],


 function initEchart(){
       option = {
            xAxis: {
                type: 'category',
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                data: dataArr          
                type: 'line'
            }]
        };  
      echarts.init(document.getElementById('youtchartId')).setOption(option);
   }

推荐阅读