简体   繁体   English

如何使用我的 mysql 数据库中的数据创建下拉列表?

[英]How to create a dropdown list with data from my mysql database?

So, I have an html form where the user will select some options.所以,我有一个 html 表格,用户将在其中 select 一些选项。 I want to create a dropdown list, in which the data we will be coming from my mysql database.我想创建一个下拉列表,其中我们将来自我的 mysql 数据库的数据。 These are my files:这些是我的文件:
在此处输入图像描述
Ignore the other files.忽略其他文件。 Index.html is my home page and my form is at air-tickets.html Index.html 是我的主页,我的表格在机票上。html
air-tickets.html机票.html

<form id="form-submit" method="post">
    <div class="container" id="air-form-container">
        <div class="col-md-12">
            <label for="sel2" class="dropbar-label">Airline: </label>
            <select class="form-control airline-select" id="sel2" name="airline">
                <option value="none">Select airline</option>
            </select>
        </div>
    </div>
</form>

air_tickets.js air_tickets.js

var express = require('express');
const path = require('path');
var air_tickets_router = express.Router();
const bodyParser = require('body-parser');

var db = require('../database');

air_tickets_router.use(bodyParser.json());

air_tickets_router.route('/')
    .get(function(req, res, next) {
        res.sendFile('air-tickets.html', { root: path.join(__dirname, '../public') });
    })
    .post(function(req, res, next) {
        console.log(req.body);
        console.log(req.body.sellist1);
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.redirect('/air-tickets');
    });

air_tickets_router.get('/get_airlines', function(req, res, next) {
    var sql = 'SELECT airline FROM flight ORDER BY airline';
    db.query(sql, function(err, data, fields) {
        if (err) throw err;
        res.render('airline-list', { title: 'Airline List', userData: data });
    });
});

module.exports = air_tickets_router;

database.js数据库.js

const mysql = require('mysql');

var mysqlConnection = mysql.createConnection({
    host: "localhost",
    user: "myuser",
    password: "mypassword",
    database: "myproject",
    multipleStatements: true
});

mysqlConnection.connect(function(err) {
    if (err) throw err;
    console.log('Database is connected successfully !');
});

module.exports = mysqlConnection;

And the app.js和 app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const mysqlConnection = require("./database")
const bodyParser = require('body-parser');

//Require routes
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var air_ticketsRouter = require('./routes/air_tickets');

var app = express();
app.use(bodyParser.json());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//Use the routes
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/air-tickets', air_ticketsRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

Also I have this air_tickets_form.js in public-->js file我也有这个 air_tickets_form.js 在公共 - > js 文件

const airlineSelect = document.querySelector("#sel2");

document.addEventListener("DOMContentLoaded", (event) => {
    fetch('http://localhost:3000/air-tickets/get_airlines')

    .then(req => req.json())
        .then(res => {
            for (let airline of res) {
                let airlineOption = document.createElement("option");
                console.log(airline);
                airlineOption.value = airline;
                airlineOption.innerHTML = airline;
                airlineSelect.appendChild(airlineOption);
            }
        })
        .catch(err => console.log(err));
});

Generally you could add an <option> to your select in javascript like this:通常,您可以像这样在 javascript 中的 select 中添加<option>

function addOption() {
  var select = document.getElementById("sel2"); //get your <select> by its ID
  var option = document.createElement("option"); // create a New <option>
  option.appendChild(document.createTextNode("Airline Name")); // provide <option> Text 
  option.setAttribute("id", "yourOptionID"); // giving your <option> an id
  select.appendChild(option); // add the created <option> to your <select>
}

Now you only have to loop through your Database Results and add options as described现在您只需要遍历您的数据库结果并按照描述添加options

Well, You can approach this problem using 2 methods:好吧,您可以使用 2 种方法来解决此问题:

1 - First Method (Not recommended) You can wait for your HTML page to load, then run Javascript to fetch your data and convert it to Options under the select Tag 1 - 第一种方法(不推荐)您可以等待 HTML 页面加载,然后运行 Javascript 以获取您的数据并将其转换为 select 标签下的选项

This is exactly what your air_tickets_form.js is doing, all you need is to include this file inside your html这正是您的 air_tickets_form.js 正在做的事情,您只需将此文件包含在您的 html 中

just add this line at the end of your body只需在你的身体末尾添加这一行

<script src="./js/air_tickets_form.js"></script>

and express will serve this file from the static folder "Public" express 将从 static 文件夹“Public”中提供此文件

Disadvantage: your website will load and for few seconds, the list will be empty if the fetch request failed, then it will remain empty until reload缺点:你的网站会加载几秒钟,如果获取请求失败,列表将为空,然后它将保持为空,直到重新加载

2 - Second Method (Recommended) Use the Render Engine within your app.js - i can see that you use Render Engine in this line 2 - 第二种方法(推荐)在你的 app.js 中使用渲染引擎 - 我可以看到你在这一行中使用了渲染引擎

app.set('view engine', 'jade');

Jade became old, and replaced now with pug You can install it using NPM then replace this line with this Jade 变老了,现在用 pug 替换你可以使用 NPM 安装它,然后用这个替换这一行

app.set('view engine', 'pug')

Now you are using the view engine现在您正在使用视图引擎

then you need to convert your html to PUG Syntax那么您需要将 html 转换为 PUG 语法

for now you can use online converter such as this one https://html-to-pug.com/现在您可以使用在线转换器,例如https://html-to-pug.com/

but I recommend you to read Pug Documentation to understand how the syntax is working (Be caution that spaces count is important in pug )但我建议您阅读 Pug 文档以了解语法是如何工作的(注意空格数在 pug 中很重要)

and when you want to send the HTML file, you send the pug file instead using this code当您想发送 HTML 文件时,您可以使用此代码发送 pug 文件

res.render('index.pug' , data) 

as data is your air tickets data因为数据是您的机票数据

then inside your Pug file, at the select tag, you will want to make a loop that insert the HTML Automatically然后在您的 Pug 文件中,在 select 标记处,您将要创建一个循环,自动插入 HTML

form#form-submit(method='post')
  #air-form-container.container
    .col-md-12
      label.dropbar-label(for='sel2') Airline: 
      select#sel2.form-control.airline-select(name='airline')
        option(value='none') Select airline
          each val,index in data
            option(value=index) #{val}

the each function will loop in the data and then add the line below it for each data each function 将循环输入数据,然后在其下方为每个数据添加行

Advantage: Your website will load with all the data ready to use without waiting优势:您的网站将加载所有可供使用的数据,无需等待

Another approach you can use is to Mix between the two methods - use the render engine to make the data ready您可以使用的另一种方法是在两种方法之间混合 - 使用渲染引擎使数据准备好

and make a button when pressed it will refresh the data using js并在按下时制作一个按钮,它将使用js刷新数据

of course according to your need.当然根据你的需要。

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

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