javascript - 提交 POST 并在 Nodejs/EJS 中处理结果

标签 javascript node.js mongodb express ejs

我有一个索引站点 (EJS),它将数组读取到选择表单中。

索引.ejs

<html>
  <head>
  </head>
 <body>
    <center>        
        <form action="/dates" method="POST">
            <b>INDEX:</b>
                <select id="index" name="index" onchange="this.form.submit()">
                    <option id="0"> Please choose Index </option>
                    <% collectionnames.map(item=> { %>
                    <option id="<%= item._id%>"> <%= item %> </option>
                    <% }) %>
                    </select>
                <br>
        </form>
 </body>
</html>

选择索引后,会将索引值发布到 app.js 中的/dates

app.js

var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var app = express();
var bodyParser = require('body-parser');

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

app.get('/', function(req, res) {
var collectionnames = [];
MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true   }, function (err, client) {
        if (err) {
            console.log("Error");
        } else {
            console.log("Connected to MongoDB to get collections...");
        }
var db = client.db('my-mongodb');
    db.listCollections().toArray(function (err,collections) {
            collections.forEach(function(collection){       
                    var elem = new Object();
                    if (collection.name !== "system.indexes"){
                    //console.log(collection.name);
                    elem = collection.name;
                    collectionnames.push(elem);
                    };
                });
                console.log("got collections...")
                res.render('index.ejs' , { collectionnames: collectionnames } );
            });
        });
    });


            app.post('/dates', function (req, res) {
                  const postBody = req.body;
                  index = postBody.index;
                  var dates = [];
                    MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }, function (err, client) {
                        if (err) {
                            console.log("Error");
                        } else {
                            console.log("Connected to fetch results");
                        }
                        var db = client.db('my-mongodb');
                        db.collection (postBody.index, function(err, values){
                            values.find().sort({VALUETIME:+1}).toArray( function (err,results){
                                results.forEach(function(result){       
                                    dates.push(result.VALUEDATE);
                                    //console.log(elem)
                                });
                                console.log("got results...")
                                function onlyUnique(value, index, self) { 
                                    return self.indexOf(value) === index;
                                }
                                var unique = dates.filter( onlyUnique );
                                console.log(unique);
                                res.send(unique);
                        });
                    });
                });
            });

我怎样才能将数组“unique”传递回我的index.ejs以在另一个选择表单中处理它?现在发生的事情(使用 res.send(unique))是我在浏览器中收到一个包含数组值的列表:

0   "2018-09-01"
1   "2018-09-02"
2   "2018-09-05"
3   "2018-09-03"
4   "2018-09-04"
5   "2018-08-31"

更具体地说:如何将数组/值检索回我的index.ejs并用它做一些事情?

谢谢。

最佳答案

您可以在 collectionnames 上使用 for 循环,例如:

//Assuming your `collectionnames = ['2018-09-01', '2018-09-02', '2018-09-03', '2018-09-04']`

<select id="selectId">
    <option value="">Select</option>
    <% if (collectionnames.length) { %>
        <% for (var i = 0; i < collectionnames.length; i++) { %>
            <option value="<%=collectionnames[i]%>"><%=collectionnames[i] %> </option>
        <% } %>
    <% } %>
</select>

编辑:如何将数据发送回同一 ejs 页面?

为了使用相同的ejs页面,您需要使用单页面应用程序方法。对于单页,您需要使用 Ajax 调用而不是 form-submit 提交数据。查看this repository以及如何实现单页应用程序的各种示例。

此外,如果您不想进入单页应用程序,只需更改您的 api 响应,使用新数据呈现同一页面:

app.post('/dates', function (req, res) {
    const postBody = req.body;
    index = postBody.index;
    var dates = [];
    MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }, function (err, client) {
        if (err) {
            console.log("Error");
        } else {
            console.log("Connected to fetch results");
        }
        var db = client.db('my-mongodb');
        db.collection (postBody.index, function(err, values){
            values.find().sort({VALUETIME:+1}).toArray( function (err,results){
                results.forEach(function(result){       
                    dates.push(result.VALUEDATE);
                    //console.log(elem)
                });
                console.log("got results...")
                function onlyUnique(value, index, self) { 
                    return self.indexOf(value) === index;
                }
                var unique = dates.filter( onlyUnique );
                console.log(unique);

                // Change here
                res.render('index.ejs' , { collectionnames: unique });
        });
    });
});
}); 

关于javascript - 提交 POST 并在 Nodejs/EJS 中处理结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52186895/

相关文章:

javascript - 完整的 Javascript Promise 错误处理。如何?

javascript - 如何在AngularJS中切换两个元素的显示

javascript - 拖动时图像的旋转值

node.js - Expressjs添加:id param to url broke static content

mysql - 运行 MongoDB 所花费的时间

javascript - 如何在 Visualforce Markup 中导入 javascript 文件?

node.js - 分离 Node.js 服务器和客户端

c++ - Node.js 插件计时器上下文

java - 如何在聚合中映射_id参数

javascript - bson的javascript/javascriptwithscope类型有什么用