绑定 JSON 文件到 Echarts (JQuery get)

bind JSON file to Echarts (JQuery get)

我想将我的JSON文件导入到Echarts做折线图但是失败了,结果页面一片空白。我在 google 中搜索它,但找不到合适的答案。

这是JSON:

[
  { "category": "A", "value": 1 },
  { "category": "B", "value": 2 },
  { "category": "C", "value": 3 },
  { "category": "D", "value": 7 }
]

var dataArr = [];
var myChart = echarts.init(document.getElementById('demo'));

$.get('data.json', {}, function(response) {
  dataArr = JSON.parse(response);
  initEchart();
});

function initEchart() {
  // specify chart configuration item and data
  var option = {
    title: {
      text: 'entry example'
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: dataArr.category
    },
    yAxis: {},
    series: [{
      type: 'line',
      data: dataArr.value
    }]
  };

  myChart.setOption(option);
}
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js" integrity="sha256-eKrx6Ly6b0Rscx/PSm52rJsvK76RJyv18Toswq+OLSs=" crossorigin="anonymous"></script>
<div id="demo" style="width: 600px;height:400px;"></div>

谢谢你帮我解决这个问题。

我修复了你的版本。您试图向图表传递空数据,因为键 dataArr.category 不存在。您收到了数组,因此需要使用循环收集数据:dataArr.map(row => row['category']) 就可以了。

var dataArr = [];
var myChart = echarts.init(document.getElementById('demo'));

$.get('https://gist.githubusercontent.com/creadone/d15105b0c7e33848ef9559c28a9912c2/raw/64a17c5ac38b375cd6ab858d51a66836d9259ed0/data.json', {}, function(response) {
  dataArr = JSON.parse(response);
 console.log(dataArr);
  initEchart();
});

function initEchart() {
  // specify chart configuration item and data
  var option = {
    title: {
      text: 'entry example'
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: dataArr.map(row => row['category'])
    },
    yAxis: {},
    series: [{
      type: 'line',
      data: dataArr.map(row => row['value'])
    }]
  };

  myChart.setOption(option);
}
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js" integrity="sha256-eKrx6Ly6b0Rscx/PSm52rJsvK76RJyv18Toswq+OLSs=" crossorigin="anonymous"></script>
<div id="demo" style="width: 600px;height:400px;"></div>