如何将图表与 js 和 jQuery 集成?

Posted

技术标签:

【中文标题】如何将图表与 js 和 jQuery 集成?【英文标题】:How to integrate charts with js and jQuery? 【发布时间】:2022-01-20 19:58:22 【问题描述】:

我正在尝试从 API 获取数据并根据从下拉列表中选择的值编辑端点并为其显示相应的图表,我可以将 js、jQuery 和图表集成在一起吗?以下是我尝试过的代码:

async function bruh()
  $( document ).ready(function() 
  $('select').on('change', async function() 
    this.value = this.value.toLowerCase();
    const apiUrl = 'https://api.covidtracking.com/v1/states/'+this.value+'/daily.json';

  const response = await fetch(apiUrl)
  const barChatData = await response.json()
  console.log(barChatData)
  const positive = barChatData.map((x) => x.positive)
  const date = barChatData.map((x) => x.date)
  positives = positive
  dates = date
  );
)

async function dummyChartbruh() 
  await bruh()
  const ctx = document.getElementById('yourChart').getContext('2d');

  const chart = new Chart(ctx, 
      
      type: 'line',
  
      
      data: 
          labels: dates,
          datasets: [
              label: 'Positive',
              backgroundColor: 'blue',
              borderColor: 'rgb(255, 99, 132)',
              data: positives,
              fill: false
          
         
        ]
      ,
  
    
      options: 
        tooltips: 
          mode: 'index'
        
      
  )
  document.getElementById("yourChart").removeAttribute("hidden");
  $('#yourChart').show()


dummyChartbruh() 

html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
  <link rel="stylesheet" href="/styles.css" />
  <title>Covid Data</title>
</head>
<body>
  <div class="card text-center m-5">
  <div class="card-header">
  <h2>Covid Data</h2>
  <select>
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
    <option value="AR">Arkansas</option>
    <option value="CA">California</option>
    <option value="CO">Colorado</option>
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="DC">District Of Columbia</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="HI">Hawaii</option>
    <option value="ID">Idaho</option>
    <option value="IL">Illinois</option>
    <option value="IN">Indiana</option>
    <option value="IA">Iowa</option>
    <option value="KS">Kansas</option>
    <option value="KY">Kentucky</option>
    <option value="LA">Louisiana</option>
    <option value="ME">Maine</option>
    <option value="MD">Maryland</option>
    <option value="MA">Massachusetts</option>
    <option value="MI">Michigan</option>
    <option value="MN">Minnesota</option>
    <option value="MS">Mississippi</option>
    <option value="MO">Missouri</option>
    <option value="MT">Montana</option>
    <option value="NE">Nebraska</option>
    <option value="NV">Nevada</option>
    <option value="NH">New Hampshire</option>
    <option value="NJ">New Jersey</option>
    <option value="NM">New Mexico</option>
    <option value="NY">New York</option>
    <option value="NC">North Carolina</option>
    <option value="ND">North Dakota</option>
    <option value="OH">Ohio</option>
    <option value="OK">Oklahoma</option>
    <option value="OR">Oregon</option>
    <option value="PA">Pennsylvania</option>
    <option value="RI">Rhode Island</option>
    <option value="SC">South Carolina</option>
    <option value="SD">South Dakota</option>
    <option value="TN">Tennessee</option>
    <option value="TX">Texas</option>
    <option value="UT">Utah</option>
    <option value="VT">Vermont</option>
    <option value="VA">Virginia</option>
    <option value="WA">Washington</option>
    <option value="WV">West Virginia</option>
    <option value="WI">Wisconsin</option>
    <option value="WY">Wyoming</option>
</select>   

  </div>
  <canvas id="myChart" ></canvas>
  <canvas id="yourChart" hidden></canvas>
</div>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="app.js"></script>
</body>
</html>

但是,当下拉列表更改时,它不会在图表上显示任何值,我该如何纠正这个问题?

【问题讨论】:

【参考方案1】:

您应该将图表分配给一个全局变量,并在每次从下拉列表中选择不同的状态时更新其数据。之后需要调用chart.update()

有关详细信息,请参阅 Chart.js 文档中的 Updating Charts。

请查看您修改后的代码,看看它是如何工作的。

$(document).ready(function() 
  $('select').on('change', function() 
    const state = this.value.toLowerCase();
    fetch('https://api.covidtracking.com/v1/states/' + state + '/daily.json')
      .then(response => response.json())
      .then(json => 
        myChart.data.labels = json.map((x) => x.date);
        myChart.data.datasets[0].data = json.map((x) => x.positive);        
        myChart.update();
      );
  );
);

const myChart = new Chart('myChart', 
  type: 'line',
  data: 
    labels: [],
    datasets: [
      label: 'Positive',
      backgroundColor: 'blue',
      borderColor: 'rgb(255, 99, 132)',
      data: [],
      fill: false
    ]
  ,
  options: 
    tooltips: 
      mode: 'index'
    
  
);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
  <link rel="stylesheet" href="/styles.css" />
  <title>Covid Data</title>
</head>

<body>
  <div class="card text-center m-5">
    <div class="card-header">
      <h2>Covid Data</h2>
      <select>
        <option>Select State...</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="DE">Delaware</option>
        <option value="DC">District Of Columbia</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="HI">Hawaii</option>
        <option value="ID">Idaho</option>
        <option value="IL">Illinois</option>
        <option value="IN">Indiana</option>
        <option value="IA">Iowa</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="ME">Maine</option>
        <option value="MD">Maryland</option>
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="MN">Minnesota</option>
        <option value="MS">Mississippi</option>
        <option value="MO">Missouri</option>
        <option value="MT">Montana</option>
        <option value="NE">Nebraska</option>
        <option value="NV">Nevada</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NM">New Mexico</option>
        <option value="NY">New York</option>
        <option value="NC">North Carolina</option>
        <option value="ND">North Dakota</option>
        <option value="OH">Ohio</option>
        <option value="OK">Oklahoma</option>
        <option value="OR">Oregon</option>
        <option value="PA">Pennsylvania</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="SD">South Dakota</option>
        <option value="TN">Tennessee</option>
        <option value="TX">Texas</option>
        <option value="UT">Utah</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WA">Washington</option>
        <option value="WV">West Virginia</option>
        <option value="WI">Wisconsin</option>
        <option value="WY">Wyoming</option>
      </select>
    </div>
    <canvas id="myChart"></canvas>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="app.js"></script>
</body>

</html>

【讨论】:

该死,非常感谢,我是 jQuery 新手,需要学习很多东西,会尝试理解代码,不知何故,后端 js 对我来说似乎比前端更容易

以上是关于如何将图表与 js 和 jQuery 集成?的主要内容,如果未能解决你的问题,请参考以下文章

如何将帆软中生成的图表与自己写的.net程序进行集成?

使用 angularjs 创建图表

我想使用 Laravel 7 将我的查询输出传递到 jQuery 图表 js

如何在 *** 上创建“拖放选择”图表?

HTML 页面到 PDF(角度 js 和 d3 图表)

jQuery 实现Bootstrap Chart 图表