|
The specific application market for this example is that I need to read the price of a commodity from the database regularly, and then display it on the web page as a graph, similar to the price trend chart of trading instruments in stocks. I use asp.net, combined with the Highcharts plugin implementation in jQuery, the plugin can support many types of graphics, but they are static, and the examples provided need to be transformed, interested friends can go to the Highcharts official website to see (http://www.highcharts.com/), which provides a lot of demos, to be honest, to realize my needs, I should use Highstock, However, after looking at the dynamic-update example of Highcharts, I can also realize that my requirements interface is more concise, so this article uses the dynamic-update model in Highcharts, and the graphics type is spline. The final effect map is as follows (the price of Pinqijin is updated every 10 seconds, and a point is added to the line graph every 10 seconds):
Achieve step gathering: Create a new website with VS and create a asp.net page DynamicUpdate.aspx, the page code is as follows:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicUpdate.aspx.cs"
- Inherits="WebImg.DynamicUpdate" %>
- <!DOCTYPE HTML>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>动态显示价格图例</title>
- <scrip去掉t type="text/javascrip去掉t" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></scrip去掉t>
- <scrip去掉t type="text/javascrip去掉t">
- $(function () {
- $(document).ready(function () {
- Highcharts.setOptions({
- global: {
- useUTC: false
- }
- });
- var chart;
- chart = new Highcharts.Chart({
- chart: {
- renderTo: 'container',
- type: 'spline',
- marginRight: 10,
- events: {
- load: function () {
- // set up the updating of the chart each second
- var series = this.series[0];
- setInterval(function () {
- var randomCode = parseInt(Math.random() * 10000);
- var oldrandomCode = parseInt(Math.random() * 10000);
- $.ajax({
- url: "ajaxhandler/dataupdate.ashx?" + randomCode + "=" + oldrandomCode + "&flag=1",
- type: "get",
- dataType: "json",
- success: function (data, textStatus, XMLHttpRequest) {
- var ctime = new Date();
- ctime.setTime(parseInt(data.rows[0].times));
- var x = ctime.getTime(), // current time
- y = data.rows[0].price * 200;
- series.addPoint([x, y], true, true);
- },
- error: function () { }
- });
- }, 10000);
- }
- }
- },
- title: {
- text: '品旗撮合交易市场品种行情'
- },
- xAxis: {
- title: {
- text: '时间'
- },
- type: 'datetime',
- tickPixelInterval: 150,
- labels:{formatter:function(){
- var vDate = new Date(this.value);
- return vDate.getHours()+":"+vDate.getMinutes()+":"+vDate.getSeconds();
- }}
- },
- yAxis: {
- title: {
- text: '价格'
- },
- plotLines: [{
- value: 0,
- width: 1,
- color: '#808080'
- }]
- },
- tooltip: {
- formatter: function () {
- return '<b>' + this.series.name + '</b><br/>' +
- Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
- Highcharts.numberFormat(this.y, 2);
- }
- },
- legend: {
- enabled: false
- },
- exporting: {
- enabled: false
- },
- credits:{
- text:'品旗金属交易市场',
- url:'http://www.inv6.com'
- },
- series: [{
- name: '品旗金(GOLD)',
- data: (function () {
- var data = [],
- i;
- var jsonData = <%= jsonstr %>;
- for (i = -19; i <= 0; i++) {
- var ctime = new Date();
- ctime.setTime(parseInt(jsonData.rows[i+19].time1));
- data.push({
- x: ctime.getTime(),
- y: jsonData.rows[i + 19].price * 200
- });
- }
- return data;
- })()
- }]
- });
- });
- });
- </scrip去掉t>
- </head>
- <body>
- <scrip去掉t src="http://code.highcharts.com/highcharts.js"></scrip去掉t>
- <scrip去掉t src="http://code.highcharts.com/modules/exporting.js"></scrip去掉t>
- <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto">
- </div>
- </body>
- </html>
Copy codeHighcharts property renderTo indicates display containers, events represents the event that the container needs to register, where load means that it occurs after the loading is completed, here a js timer is set in the load, which occurs once every 10 seconds, and the code in it is to request the latest GOLD from the dataupdate.ashx file of the ajaxhandler folder in the same root directory as the DynamicUpdate.aspx page through ajax in jQuery The price data of the variety, here is why I add randomCode + "=" + oldrandomCode in the ajax URL because adding a random number can avoid caching, and flag=1 is because my dataupdate.ashx file wants to accept multiple requests from different ajax, so use flag to distinguish it xAxis represents the collection of attributes defined for the x-axis of the container, type represents the displayed text type, optional, here I fill in the time type, here note that the default for the instance is GMT time, you can also use UTC time, but we generally use Beijing time, (GMT or UTC) + 8 hours = Beijing time, so when we use ajax to get the time is Beijing time, we should subtract 8 hours from the hour (here I also want to share an experience, How to convert server time to js time that can be used by the .getTime() method, that is, subtract the server time from 1970-1-1, convert the remaining days to milliseconds, and then assign a value to the newly initialized time through the setTime method in js, I found that the result obtained by getTime() is incorrect to initialize a js time directly in js in the form of new Date (year, month, day, hour, minute, second, millisecond) with getTime(), As for why 1970-1-1 is subtracted, it is because the definition of the getTime() method is to get the number of milliseconds from the current time from 1970-1-1), when the x-axis is not displayed as a time or you need to define it yourself, it can also be defined by the categories attribute, tickPixelInterval represents the density of the x-axis, and labels is used to format the display format of the x-axis yAxis represents a collection of attributes defined for the y-axis of the container, which is roughly the same as the attributes of the x-axis, but in Highcharts it is not possible to define the fixed value of the y-axis through categories, the y-axis of Highcharts is automatically generated based on the given coordinate point data, which depends on the data sub-attribute of the series attribute, for example, when you assign a value to data The maximum value is 300, and the minimum value is 100. Then the display of the y-axis will be between 100 and 300, or you can also set the max or min attribute of yAxis series represents the collection of all curves displayed in the container, here I only show one curve, name represents the name of the curve, data represents the collection of a series of coordinate points of the curve, x is in front, y is behind, it is a js array, in this case, because the x-axis shows time, so the x property of the array object must be set to time, but in Highcharts it is not directly assigned time to the x-axis, Instead, the number of milliseconds between 1970-1-1 and a certain time is assigned to the x-axis to represent this time, so the getTime() method must be used, the form of the y-axis coordinate point must be y = small number * integer form, and I didn't understand why Highcharts had to do this, because the price data of the variety in this example is generally about the same, so I had to divide by 200 when obtaining the data, and then multiply by 200 when assigning a value to the y-axis.
<%= jsonstr %> in the page code is the initial data I need to get from the server to initialize the graph, the cs generation of the page
- public string jsonstr = "";
- protected void Page_Load(object sender, EventArgs e)
- {
- getData();
- }
- private void getData()
- {
- DataTable dtPrice = SQLDBHelper.ExecuteTable("select top 20 TMPCode,TMPTime,TMPPrice from TabMerPrice with(nolock) order by TMPTime desc");
- string json = "{"rows":[";
- for (int i = (dtPrice.Rows.Count-1); i >= 0; i--)
- {
- json += "{"time1":"" + (Convert.ToDateTime(dtPrice.Rows[i]["TMPTime"]).AddHours(-8) - new DateTime(1970, 1, 1)).TotalMilliseconds + "","price":"" + (Convert.ToDecimal(dtPrice.Rows[i]["TMPPrice"])/200) + ""},";
- }
- json = json.TrimEnd(',');
- json += "]}";
- jsonstr = json;
- }
Copy codeAmong them, the TabMerPrice table is the variety price information table, TMPTime time, TMPPrice price, TMPTime time interval is ten seconds, I use a database job to generate the record of the table, which happens once every ten seconds AddHours(-8) is to convert the time to Beijing time, and the generated data format is json format The dataupdate.ashx code looks like this:
- public void ProcessRequest(HttpContext context)
- {
- string flag = context.Request.QueryString["flag"].ToString();
- switch (flag)
- {
- case "1"://获取品种当前价格
- GetMerPrice(context);
- break;
- }
- }
- private void GetMerPrice(HttpContext context)
- {
- context.Response.Clear();
- context.Response.Buffer = true;
- context.Response.ContentType = "application/json";
- context.Response.ContentEncoding.GetBytes("utf-8");
- DataTable dtPrice = SQLDBHelper.ExecuteTable("select top 1 TMPCode,TMPTime,TMPPrice from TabMerPrice with(nolock) order by TMPTime desc");
- string json = "{"rows":[";
- json += "{"times":"" + (Convert.ToDateTime(dtPrice.Rows[0]["TMPTime"]).AddHours(-8) - new DateTime(1970, 1, 1)).TotalMilliseconds + "","price":"" + (Convert.ToDecimal(dtPrice.Rows[0]["TMPPrice"]) / 200) + ""}";
- json = json.TrimEnd(',');
- json += "]}";
- context.Response.Write(json);
- context.Response.Flush();
- context.Response.End();
- }
Copy codeThis is the rough implementation of step aggregation, which can realize the real-time display of server-side data with a graph similar to the stock format
HighCharts演示.zip
(48.69 KB, Number of downloads: 1)
|