亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Node.js 在 html 表中顯示 mysql

使用 Node.js 在 html 表中顯示 mysql

米琪卡哇伊 2022-01-07 20:59:57
我正在學習如何將 node.js 與 mysql 一起使用。我試圖找到一些好的文檔但徒勞無功。我現在可以在瀏覽器中顯示我的 mysql 數據,但我想在某個時候通過我的 index.html 和一個 css 文件來處理它。這是我的 app.js:// moduelsvar 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 databasevar con = mysql.createConnection({    host: "localhost",    user: "root",    password: "1234",    database: "BathBombs_DB"});// routesapp.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:9000app.listen(9000, function () {    console.log('Connected to port 9000');});我的 index.html 網站如下所示:<!DOCTYPE html><html><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>
查看完整描述

3 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

您必須進行 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);

            }  


        }

    }

})

})


查看完整回答
反對 回復 2022-01-07
?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

一種簡單的方法是使用像 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>

    <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表中獲取數據以顯示或返回。


查看完整回答
反對 回復 2022-01-07
?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

首先,您需要“發送/發送”您的“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>

<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”提供給客戶端/瀏覽器。


查看完整回答
反對 回復 2022-01-07
  • 3 回答
  • 0 關注
  • 415 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號