如何创建具有自动完成功能的文本输入,然后在 express 中显示来自 mysql 数据库的数据?

How can I create a text input with autocomplete and then display data from mysql database in express?

所以,我有一个表单,用户将在其中 select 输入。首先,我想创建一个文本输入,当用户输入例如 A 时,它会建议 MYSQL 数据库中以 A 等开头的所有数据。表单的页面是 /air_tickets 然后用户将被重定向到另一个页面。
文件结构:

views 文件夹中,有我所有的 .ejs 页面 (html)。
air_tickets.ejs

<form id="form-submit" method="post">
                            <div class="container" id="air-form-container">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="from_destination">From: </label>
                                            <br>
                                            <input type="text" name="from_destination" class="form-control typeahead tt-query" spellcheck="false" autocomplete="off" placeholder="City or airport" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="to_destination">To: </label>
                                            <br>
                                            <input type="text" name="to_destination" class="form-control" placeholder="City or airport">
                                        </div>
                                    </div>
                                   <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-btn">
                                            <button type="submit" class="btn btn-primary" id="submit-btn">Search flights 
                                            <i class="fas fa-search" aria-hidden="true"></i>
                                        </button>
                                        </div>
                                    </div>
                                </div>
                              </div>
                       </form>

我也找到了一种使用 typeahead 库的方法,但它不能正常工作。这是脚本(我把它放在 air_tickets.ejs 文件中):

<script>
        $(document).ready(function() {
            $('input.typeahead').typeahead({
                name: 'typeahead',
                remote: 'http://localhost:3000/search?key=%QUERY',
                limit: 10
            });
        });
    </script>


index.js(在路由文件中)

var express = require('express');
var router = express.Router();

// Air tickets controller
const airTicketsController = require('../controllers/airTicketsController');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('home', { title: 'Express' });
});

// Air tickets page
router.get('/air_tickets', function(req, res, next) {
    res.render('air_tickets', { title: 'Air tickets' });
});

router.get('/search', airTicketsController.fromDestinations);


airTicketsController.js

const mysql = require('mysql');

// DB connection
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'myuser',
    password: 'mypassword',
    database: 'mydatabase'
});

connection.connect(function(error) {
    if (!!error) console.log(error);
    else console.log('CONGRATS! Database Connected!');
});

//---------------
// autocomplete for from_destination
exports.fromDestinations = (req, res) => {
    connection.query('SELECT from_destination FROM flight where from_destination LIKE "%' + req.query.key + '%"',
        function(err, rows, fields) {
            if (err) throw err;
            var data = [];
            for (i = 0; i < rows.length; i++) {
                data.push(rows[i].from_destination);
            }
            res.end(JSON.stringify(data));
        });
}


app.js

const path = require('path');
const express = require('express');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();

// DB connection
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'myuser',
    password: 'mypassword',
    database: 'mydatabase'
});

connection.connect(function(error) {
    if (!!error) console.log(error);
    else console.log('CONGRATS! Database Connected! (app)');
});

//set views file
app.set('views', path.join(__dirname, 'views'));

//set public file
app.use(express.static(__dirname + '/public'));

//set view engine
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const routes = require('./server/routes/index');

app.use('/', routes);

// Server Listening
app.listen(3000, () => {
    console.log('Server is running at port 3000');
});

所有数据都将来自名为 flight 的 MYSQL table 并且具有像 from_destination[= 这样的列46=] 和 to_destination
我无法正确包含预输入库。但是,如果您知道根据我的 SQL 查询创建自动更正文本的其他方法,请向我推荐。

我发现了关于 jQuery 自动完成的内容:

<script>
        $(function() {
            var availableTags = [
                "ActionScript",
                "AppleScript",
                "Asp",
                "BASIC",
                "C",
                "C++",
                "Clojure",
                "COBOL",
                "ColdFusion",
                "Erlang",
                "Fortran",
                "Groovy",
                "Haskell",
                "Java",
                "JavaScript",
                "Lisp",
                "Perl",
                "PHP",
                "Python",
                "Ruby",
                "Scala",
                "Scheme"
            ];
            $("#tags").autocomplete({
                source: availableTags
            });
        });
    </script>


其中 tags 是文本输入的 ID。它工作正常。
虽然,我现在的问题是如何从数据库中获取数据

首先,随着原始问题的进展,您应该编辑问题标题,您应该在另一个问题中提问。

对于Although, my problem now is how I will take the data from the database部分

  1. 而不是 form id="form-submit",它将是 form action="form-submit"
  2. 在表单中放置一个按钮或输入(type=submit)。
  3. 将您的 app.js 的 bodyParser 行编辑为
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
  1. 在 app.js 末尾添加 module.exports = app; 并在 airTicketsController.js 末尾添加 module.exports = connection; (同时从 airTicketsController.js,ejs 表单和index.js暂时避免不必要的干扰)
  2. 然后你必须通过添加这个
  3. 来阅读表格
var variable1, variable2;
router.post('/form-submit', function(req,res,next){
    variable1 = req.body.from_destination;
    variable2 = req.body.to_destination
    res.redirect('/yournextpage');
});
  1. 然后在新页面使用这两个变量根据你的需要查询你的数据库
router.get('/yournextpage', function(req,res, next){
    airTicketsController.query("SELECT * FROM flight WHERE your_column1=? AND your_column2=?",[variable1,variable2],function(err, results, fields){
      res.render('yournextpage', {title: 'flightdata', retrieved: results});
    });
});

module.exports = router;