繁体   English   中英

在带有 Node.js 的 html 表中显示 mysql

[英]Display mysql in a html table with Node.js

我正在学习如何将 node.js 与 mysql 一起使用。 我试图找到一些好的文档但徒劳无功。 我现在可以在浏览器中显示我的 mysql 数据,但我想在某个时候通过我的 index.html 和 css 文件来处理它。

这是我的 app.js:

// moduels
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('bodyParser')

// 
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: false}));

// connect to database
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "1234",
    database: "BathBombs_DB"
});

// routes
app.get('/', function(request, response){
    console.log('GET request received at /') 
    con.query("SELECT * FROM customers", function (err, result) {
        if (err) throw err;
        else{
            response.send(result)
        }

    });
});

// listen for trafic and display on localhost:9000
app.listen(9000, function () {
    console.log('Connected to port 9000');
});

我的 index.html 站点如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <form action="/" method="POST">
            <table type="text" name="firstname" ></table>
    </form>

</body>
</html>

您必须进行 ajax 调用以从服务器获取结果并使用 javascript 与 HTML 内容绑定,如下所示:

HTML 模板

 <table id="tableData" class="table table-fixed">
<thead>
  <tr>
  </tr>
</thead>
<tbody class="tbody" >
</tbody>

这是进行 ajax 调用的脚本

$(document).ready(() => {

$.ajax({
    url: "http://localhost:9000/list", 
    method: 'GET',
    success: function(response){
        if(response.rows.length > 0){
            for(let index = 0; index < response.rows.length; index++) {
                var newRow = $("<tr>");
                var cols = "";
                var firstname = '';
                var lastname = '';
                var gender = '';
                cols += '<td> '+ response.rows[index].firstname +'</td>';
                cols += '<td> '+ response.rows[index].lastname +'</td>';
                cols += '<td> '+ response.rows[index].gender+'</td>';                
                newRow.append(cols);
                $("#tableData .tbody").append(newRow);
            }  

        }
    }
})
})

您可以在<table>标签中简单地显示如下:

<html>
    <body>
        <table>
          <tr>
            <th>firstname</th>
          </tr>
          <% if(result.length){ 
            for(var i = 0;i < data.length;i++) { %>
          <tr>
            <td><%=result.firstname%></td>
          </tr>
           <% }
          }else{ %>
          <tr>
            <td>No user</td>
          </tr>
        <% } %>
        </table>
    </body>
</html>

首先,您需要“发送/发送”您的“index.html”文件到浏览器。 为此,您需要定义一个 API 端点,如下所示(它将 index.html 发送到浏览器)。

/* GET home page. */
app.get('/', getMainPage);

function getMainPage(req, res) {

  console.debug('Route for mainViewpage: ' + __dirname );
  console.log(process.env);
  var mainViewFile = __dirname + '/../public/views/index.html'; // Replace  this with path to your index.html file
  console.log('mainView log' , mainViewFile);
  fs.readFile(mainViewFile, function (err, html) {
    if (err) {
      throw err;
    }
    res.writeHeader(200, {"Content-Type": "text/html"});
    res.write(html);
    res.end();
  });
}

完成此操作后,请遵循@priya tarun 在上一个答案中给出的方法。

注意:您还需要在 html 文件中包含 Jquery。 您的“index.html”看起来像这样。 我还没有完全测试,你可以做那部分。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <!--Inlcudes JQuery -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> 

</head>
<body>

    <form action="/" method="POST">
            <table type="text" name="firstname" ></table>
    </form>

</body>

$(document).ready(() => {

$.ajax({
    url: "http://localhost:9000/getCustomerData", 
    method: 'GET',
    success: function(response){
        if(response.rows.length > 0){
            for(let index = 0; index < response.rows.length; index++) {
                var newRow = $("<tr>");
                var cols = "";
                var firstname = '';
                var lastname = '';
                var gender = '';
                cols += '<td> '+ response.rows[index].firstname +'</td>';
                cols += '<td> '+ response.rows[index].lastname +'</td>';
                cols += '<td> '+ response.rows[index].gender+'</td>';                
                newRow.append(cols);
                $("#tableData .tbody").append(newRow);
            }  

        }
    }
})
})
</html>

注意:将您的 API 端点重命名为“/getCustomerData”而不是“/”来获取客户数据。 使用 API 端点“/”将“index.html”提供给客户端/浏览器。

如果您对此有任何困惑,请添加评论

一种简单的方法是使用像 Knex JS 这样的查询构建器。 它提供了更好的体验并且更易于使用。 我相信以下代码对您有意义:

const knex = require('knex');
const http = require('http');

const knex = require('knex')({
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
});

const record = await knex.select('title', 'author', 'year').from('books');
const displayBody = record.map(single => {
   return `<tr>
             <td>${single.title}</td>
             <td>${single.author}</td>
             <td>${single.year}</td>
           </tr>`;
})

let handleRequest = (request, response) => {
    response.writeHead(200, {
        'Content-Type': 'text/html'
    });
    response.write('<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Homepage</title>
    </head>
    <body>
     <table>
        <thead>
            <tr>
                <th>Title</th>
                <th>Author</th>
                <th>Year</th>
            </tr>
        </thead>
      <tbody>');
    response.write(displayBody);
    response.write('</tbody>
        </table>
      </body>
    </html>');
    response.end();
};

http.createServer(handleRequest).listen(8000);

在上面的代码中,我们从books表中获取数据以显示或返回。

这你可以使用普通的 javascript 来处理,请在下面找到代码片段,我使用了硬编码数据,但是你可以使用 API 响应来处理,因为成功后你可以触发 GenerateTable() 在 Z4C4AD5FCA2E7A3F74DBB1CED00381AAZ 中呈现:

 function GenerateTable() { //Build an array containing Customer records. var customers = new Array(); customers.push(["Customer Id", "Name", "Country"]); customers.push([1, "John Hammond", "United States"]); customers.push([2, "Mudassar Khan", "India"]); customers.push([3, "Suzanne Mathews", "France"]); customers.push([4, "Robert Schidner", "Russia"]); //Create a HTML Table element. var table = document.createElement("TABLE"); table.border = "1"; //Get the count of columns. var columnCount = customers[0].length; //Add the header row. var row = table.insertRow(-1); for (var i = 0; i < columnCount; i++) { var headerCell = document.createElement("TH"); headerCell.innerHTML = customers[0][i]; row.appendChild(headerCell); } //Add the data rows. for (var i = 1; i < customers.length; i++) { row = table.insertRow(-1); for (var j = 0; j < columnCount; j++) { var cell = row.insertCell(-1); cell.innerHTML = customers[i][j]; } } var dvTable = document.getElementById("dvTable"); dvTable.innerHTML = ""; dvTable.appendChild(table); } function handleApiResponse() { //$.ajax({ // type: "GET", // url: URL, // dataType: "jsonp", // error: function (response) { // alert('Error: There was a problem //processing your request, please refresh the browser and //try again'); // }, // success: function (response) { // GenerateTable(response) // } // }); GenerateTable() }
 <input type="button" value="Generate Table" onclick="handleApiResponse()" /> <hr /> <div id="dvTable"></div>

暂无
暂无

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

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