echarts报表数据实时刷新可能有的人会想到使用定时器,其实有更简便的方法来解决这个问题, “WebSocket” 它可以做到服务器端主动向客户端发送数据。
不多说,直接上代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Bar.aspx.cs" Inherits="WebSocket.Bar" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="jquery-2.1.4.min.js"></script>
<script src="echarts.min.js"></script>
<script>
var myChart1;
window.onload = function () {
myChart1 = echarts.init(document.getElementById('bar'));
ws();
}
function ws() {
var socket;
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket;
}
if (window.WebSocket) {
socket = new WebSocket("ws://192.168.64.131:8080/ws");
socket.onmessage = function (event) {
var data = (event.data + '').split(',');
SetOptions(data);
};
socket.onopen = function (event) {
console.info("连接开启");
//var ta = document.getElementById('responseText');
//ta.value = "连接开启!";
};
socket.onclose = function (event) {
console.info("连接被关闭");
//var ta = document.getElementById('responseText');
//ta.value = ta.value + "连接被关闭";
};
} else {
alert("你的浏览器不支持 WebSocket!");
};
}
function SetOptions(data)
{
option = {
color: ['#3398DB'],
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
axisTick: {
alignWithLabel: true
}
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: '直接访问',
type: 'bar',
barWidth: '60%',
data: data
}
]
};
myChart1.setOption(option);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="bar" style="width:500px;height:400px;">
</div>
</form>
</body>
</html>
这是前端调用的代码,后端WebSocket需自行创建。
更多文章请扫码关注公众号,有问题的小伙伴也可以在公众号上提出。