如何在使用Express时以表格形式访问EJS数据 [英] How do i access ejs data in a form while using express

查看:67
本文介绍了如何在使用Express时以表格形式访问EJS数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,我应用户要求显示以下HTML文件。我还想访问俱乐部名称,并在app.js文件的app.post()函数内键入数据值。

In the following code, I display the following HTML file upon user requests. I also want to access the clubname and type datavalues inside my app.post() function in my app.js file.

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<% include templates/adminheader.ejs %>
<h1>Respond to Club Requests</h1>

<form name="clubform" method="post">
    <% for (var i in clubreq){%>
        Club Name:<%= clubreq[i].clubname %><br><br>//I want to access this variable in my app.post() function
        Club Type:<%= clubreq[i].type %><br><br>
        <input type="submit" value="accept"/><br><br><hr>
    <%} %>
</form>

</body>
</html>

app.js 内部。在这里,我根据用户请求呈现HTML文件

Inside app.js. Here I am rendering the HTML file upon user request

app.get('/clubreq', function(req, res, next){
        res.render('clubreq', {
            title: 'Club Requests',
            "clubreq" : docs
        });       
});
app.post('/clubreq', function(req, res, next){
    //I want to access clubname and type datavariables here and store it in my mongodb database
});


推荐答案

首先让我们将信息放入表格中。像这样编辑表单:

Let's start with getting the info into the form. Edit the form like so:

<form action="/clubreq" method="post">
    <% for (var i in clubreq){%>
        Club Name: <input type="text" name="clubname[]" value="<%= clubreq[i].clubname %>" /><br><br>
        Club Type: <input type="text" name="clubtype[]" value="<%= clubreq[i].type %>" /><br><br>
        <input type="submit" value="accept"/><br><br><hr>
    <%} %>
</form>

重点是添加操作属性,该属性指示提交表单的位置,并添加了输入以确保值并随表格一起运输。如果您不喜欢它的外观,可以将输入类型更改为隐藏,然后添加另一个类似回声的名称,如俱乐部名称和俱乐部类型,以供最终用户查看。

The important points being adding the action attribute indicating where to submit the form and the addition of inputs to ensure the values and transported with the form. If you don't like the way it looks, you can change the input type to hidden and then add another echo like you had before of club name and club type for the end user to see.

现在介绍如何访问表单数据服务器端,在所有其他中间件的顶部添加以下内容:

Now on to how to access your form data server side, add the following to the top with all your other middleware:

app.use(express.bodyParser());

接下来,您可以像这样访问方法中的帖子数据:

Next, you can access the post data in your method like so:

app.post('/clubreq', function(req, res, next){
   // req.body object has your form values
   console.log(req.body.clubname);
   console.log(req.body.clubtype);
});

希望有帮助

这篇关于如何在使用Express时以表格形式访问EJS数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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