首页 > 解决方案 > 单击按钮后如何打开新的ejs文件?

问题描述

我正在创建一个表单,单击提交后我想打开另一个 ejs 页面。现在我无法做到这一点。我将我的第二个文件放在 app.js 中。

应用程序.js

app.get('/form1', function (req, res) {
    res.render('form', {
        title: "Login", 
        action: "/form1", 
        fields: [
            { name: 'Name', type: 'text', property: 'required' },
            { name: 'Email', type: 'text', property: 'required' }
            { name: 'Phone No', type:'text', property: 'required' }
        ]
    });
});

ejs文件如下

form1.ejs

<form action="<%= action %>" method="post">
    <% if (fields.length) { %>
        <% fields.forEach(function(field) { %>
            <label><%= field.name %></label>
            <input type="<%= field.type %>" name="<%= field.name %>"
                <% if (field.property) { %>
                    <%= field.property %>
                <% } %>
            >
        <% }) %>
    <% } %>
    <button type="submit"><%= title %></button> <!-- Title for button is same as that of the page -->
</form>

单击提交按钮后我要打开的第二个文件。

<form action="<%= action %>" method="post">
    <h> Data goes here </h>
</form>

标签: node.jsejs

解决方案


为form1(第一个ejs页面/表单)创建另一个路由(POST)

app.post('/form1', function (req, res) {
    // Do the task with the form data submitted
    // Redirect to form2/file 2
    res.redirect(URL_to_second_form or file2);
}

现在,当用户在 form1 页面点击提交时,它会自动打开第二个 ejs 页面或文件 2。


推荐阅读