使用Node.js在html表中显示mysql [英] Display mysql in a html table with Node.js

查看:85
本文介绍了使用Node.js在html表中显示mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i'm learning how to use node.js with mysql. I've tried to find some good documentation but in vain. i'm at the point where I can get my mysql data displayed in my browser but I want to handle it through my index.html and a css file at some point.

这是我的app.js:

This is my 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网站看起来像这样:

My index.html site looks like this:

<!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内容进行绑定:

You have to make an ajax call to get a result from the server and bind with HTML content using javascript as below :

HTML模板

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

这是进行ajax调用的脚本

Here is the script to make an ajax call

$(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);
            }  

        }
    }
})
})

这篇关于使用Node.js在html表中显示mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆