简体   繁体   English

在node.js中从mysql接收数据以绘制图形

[英]Receive data from mysql in node.js to draw graph

I'm learning node.js and i want to write a program that draws a graph of data fetched from mysql database. 我正在学习node.js,我想编写一个程序来绘制从mysql数据库获取的数据图。 I am doing the back end processing in the server.js file and showing results in index.html. 我正在server.js文件中进行后端处理,并在index.html中显示结果。 Since i'm new to node.js and web programming. 由于我是node.js和Web编程的新手。 I don't know how to get data as a javascript object and draw it's graph. 我不知道如何获取数据作为javascript对象并绘制它的图形。

Question: I want to know how would i send the data fetched into the javascript object to the graph drawing code. 问题:我想知道如何将提取到javascript对象中的数据发送到图形绘制代码。

Here is my server.js : 这是我的server.js:

var mysql = require('mysql');
var express = require('express');
var app =express();
var country = [], population = [], gdp = [];
var jsonArray;

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '12345',
  database: 'rohan'
});
var queryString = 'SELECT * FROM Country';

// Fetching data from database
app.get('/', function(req, res) {
  connection.query(queryString, function(err, rows, fields) {
    if(err) throw err;
    formatData(rows);
    res.send(jsonArray);
    console.log(jsonArray);
  });
});

function formatData(dataArray) {
  for(var i = 0; i < dataArray.length; i++) {
    country[i] = dataArray[i].name;
    population[i] = dataArray[i].population;
    gdp[i] = dataArray[i].GDP;
  }
  jsonArray = [country, population, gdp];
  console.log("in FormatData()...\n");
  console.log(jsonArray);
}

app.listen(3000, function() {
  console.log("Server listening on port 3000");
});

and this is my index.html: 这是我的index.html:

<html>
  <head>
    <title>Chart-mysql demo</title>
    <script>
      // code to draw graph
      $("#clients").bind('ajax:success', function(result) {
        console.log("In index.html" +  result);
        alert(result);
        var barData = {
          label:result.country,
          datasets: [
            {
              label: '2010 Customers #',
              fillColor: '#382765',
              populationData:result.population
            }
          ]
        };
       var context = document.getElementById('clients').getContext('2d');
       var clientsChart = new Chart(context).Bar(barData);

      });
    </script>
  </head>

  <body>
    <h1>Country Demographics</h1>
    <script src="Chart.js"></script>
    <script src="app.js"></script>
    <canvas id="clients" width=500 height=400></canvas>
  </body>
</html>

You should first write a module which would fetch the data(you have got a piece of code which connects to the database so we can skip this part). 首先,您应该编写一个模块来获取数据(您有一段连接到数据库的代码,因此我们可以跳过此部分)。

Then we should write a router which would pass the data to the pathname (when it is called) for example like this: 然后,我们应该编写一个路由器,该路由器会将数据传递到路径名(在被调用时),例如:

router.get('/', function(req, res, next) {
    api.apiGet(function (data){ 

-> importing data from module (api is a variable importing the module, apiGet a function from api). ->从模块导入数据(api是导入模块的变量,api从api获取函数)。

        res.render('portal', {result: data}); -> data is passed as result
    });
});

Then you would write a view which would use that data, for example in Jade it would be the following. 然后,您将编写一个使用该数据的视图,例如在Jade中将是以下视图。

{val[4].label}

It just grabs the data which is send in JSON. 它只是获取以JSON发送的数据。

If you need something clearing just write :) 如果您需要清除某些内容,请写:)

As I see you haven't get data from node.js app. 如我所见,您尚未从node.js应用程序获取数据。 First of all you need to somehow retrieve this html from server, so you need to add something like: 首先,您需要以某种方式从服务器检索此html,因此您需要添加以下内容:

app.get('/', function(req, res) {
    res.render('index.html');
});

Then you need to change your current app.get('/' to some another url. Let's say "/data". After that change you need to change your current index.html, and add there JS code, which will request data from "/data". You can use jquery for that. Take a look at http://api.jquery.com/jquery.ajax/ Then you will get an JS object in callback of Jquery ajax request to node.js "/data". 然后,您需要将当前的app.get('/'更改为其他网址。假设为“ / data”。更改之后,您需要更改当前的index.html,并添加JS代码,该代码将请求“ / data”。您可以使用jquery。看看http://api.jquery.com/jquery.ajax/,然后您将在向node.js“ / data的Jquery ajax请求的回调中获得一个JS对象。 ”。

After hours of head scratching i finally did it.As far as server side was concerned i was doing it right. 经过数小时的努力,我终于做到了。就服务器端而言,我做得很好。 I just didn't know how to deal with data on the client. 我只是不知道如何在客户端上处理数据。 To receive data as a javascript object, I added a button and connected an AJAX call to it's onclick() event. 为了将数据作为JavaScript对象接收,我添加了一个按钮并将AJAX调用连接到它的onclick()事件。

  <body>
    <h1>Country Demographics</h1>
    <button id="Get_Graph" onclick="gData(); return false">Get Graph<button/>
    <canvas id="clients" width=500 height=400></canvas>
  </body>

And to handle it's click event, here is javascript code: 为了处理click事件,这是javascript代码:

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../Chart.js"></script>

<script>
  // code to draw graph

  function gData() {
    $.get("http://localhost:3000", function(result, status) {
      alert(result);
      var barData = {
        labels:result[0],
        datasets: [
          {
            label: '2010 Customers #',
            fillColor: '#382765',
            data: result[2]
          }
        ]
      };
     var context = document.getElementById('clients').getContext('2d');
     var clientsChart = new Chart(context).Bar(barData);
    });
 }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM