【Chart.js】通过Ajax请求JSON数据来绘制图


在使用Chart.js绘制图表时,我们通常会有这样的需求:从后台方法动态获取图表的数据,而非Demo中使用的静态数据。本文将分享如何使用Ajax动态请求JSON数据并且完成图表的绘制。

解决方案

在html页中添加对Chart.js的引用(下载js文件或者添加CDN引用)

https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js

1 使用HTML5<canvas>标签定义一个图形容器,用来绘制图形

<canvas id="myChart" width="740" height="200"></canvas> 1 在JS文件中添加 function drawRadarChart() ;

function drawLineChart() {

      // 格式化时间数据      

Date.prototype.formatMMDDYYYY = function() {           return (this.getMonth() + 1) +           "/" +  this.getDate() +           "/" +  this.getFullYear();       }      

//使用Ajax获取json数据       var jsonData = $.ajax({         url: '/mySensor/SensorRecord_getSensorRecord',         dataType: 'json',       }).done(function (results) {

 // 将获取到的json数据分别存放到两个数组中         var labels = [], data=[];         for(var sensorRecord in results)         {             labels.push(new Date(results[sensorRecord].date).formatMMDDYYYY());             data.push(parseFloat(results[sensorRecord].sensorValue));         }

        // 设置图表的数据        

var tempData = {           labels : labels,           datasets : [{               label: "温度",                 fill: true,                 lineTension: 0.1,                 backgroundColor: "rgba(75,192,192,0.4)",                 borderColor: "rgba(75,192,192,1)",                 borderCapStyle: 'butt',                 borderDash: [],                 borderDashOffset: 0.0,                 borderJoinStyle: 'miter',                 pointBorderColor: "rgba(75,192,192,1)",                 pointBackgroundColor: "#fff",                 pointBorderWidth: 1,                 pointHoverRadius: 5,                 pointHoverBackgroundColor: "rgba(75,192,192,1)",                 pointHoverBorderColor: "rgba(220,220,220,1)",                 pointHoverBorderWidth: 2,                 pointRadius: 1,                 pointHitRadius: 10,                 data: data,                 spanGaps: false,           }]         };

        // 获取所选canvas元素的内容         var ctx = document.getElementById("myChart");         //设置图表高度         ctx.height=9;                                         

// 初始化一个新的雷达图         var myLineChart = new Chart(ctx, {             type: 'radar',             data: tempData,             options: {                 maintainAspectRatio: true,             }         });       });     } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 配置JSON数据源   json数据是由Struts2 Action返回的一个包含温度数据的List,实体包含以下属性:

private int recordID; private String sensorID; private String sensorValue; private Timestamp date; --------------------- 作者:Bboy-AJ-任杰 来源:CSDN 原文:https://blog.csdn.net/u013201439/article/details/72794408 版权声明:本文为博主原创文章,转载请附上博文链接!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM