我们怎样才能延迟执行html代码

问题描述 投票:0回答:1
javascript html node.js ejs web-development-server
1个回答
0
投票

我使用了一个名为 Submitted 的附加变量,并在页面加载时将其设置为

false

app.get('/Recipes', (req, res) => {
    // Render the EJS template with submitted set to false (initial page load)
    res.render('recipe', { submitted: false });
});

每当输入菜谱名称并提交表单时,将提交的变量设置为 true。

app.post('/Recipes', (req, res) => {

    // Set submitted to true to render the specific code
    res.render('recipe', { submitted: true, Name: 'Recipe Name', Instructions: ['Step 1', 'Step 2'] });
});

这是我如何实现它的完整代码-

EJS模板文件:

<body>
    <form action="/Recipes" method="post">
        <input type="text" name="recipeName" placeholder="Enter recipe Name" required>
        <button>Find</button>
    </form>

    <% if (submitted) { %>
        <!-- The below code will only run if the form is submitted -->
        <section class="GPT">
            <h1><%= Name %></h1>

            <% Instructions.forEach(function(instruction) { %>
                <ul><%= instruction %></ul>
            <% }); %>

            <a href="/"><button>Home</button></a>
        </section>
    <% } %>
</body>

服务器端代码(NodeJS)

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

app.get('/Recipes', (req, res) => {
    // Render the EJS template with submitted set to false (initial page load)
    res.render('recipe', { submitted: false });
});

app.post('/Recipes', (req, res) => {
    // Process the form submission here

    // Set submitted to true to render the specific code
    res.render('recipe', { submitted: true, Name: 'Recipe Name', Instructions: ['Step 1', 'Step 2'] });
});
© www.soinside.com 2019 - 2024. All rights reserved.