You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现HTML代码延迟执行?表单提交后运行指定EJS代码

解决方案:仅在表单提交后渲染指定EJS代码

你的核心问题是EJS作为服务端模板,页面加载时会自动执行所有<% %>内的代码,要实现仅在表单提交后渲染目标区块,有两种可靠方案:

方案一:服务端条件渲染(推荐)

通过后端路由区分GET(页面初始加载)和POST(表单提交)请求,传递标志位控制EJS是否渲染目标区块。

1. 后端路由修改(以Express为例)

const express = require('express');
const app = express();
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true })); // 解析表单数据

// 初始加载页面:不传递食谱数据,标记未提交
app.get('/Recipes', (req, res) => {
  res.render('recipes', {
    isSubmitted: false,
    Name: '',
    Instructions: []
  });
});

// 处理表单提交:获取数据后,标记已提交并传递数据
app.post('/Recipes', (req, res) => {
  const recipeName = req.body.recipeName;
  // 这里替换成你实际获取食谱数据的逻辑(数据库/API调用)
  const recipeData = {
    Name: recipeName,
    Instructions: ['准备食材', '加热烹饪', '完成装盘']
  };
  res.render('recipes', {
    isSubmitted: true,
    ...recipeData
  });
});

2. EJS模板修改

添加EJS条件判断,仅当isSubmitted为true时渲染目标区块:

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

    <% if (isSubmitted) { %>
    <section class="GPT">
        <h1><%= Name %></h1>

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

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

方案二:前端控制显示隐藏

如果不想修改后端逻辑,可以通过CSS初始隐藏区块,再用JS判断是否有数据来显示:

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

    <section class="GPT" style="display: none;">
        <h1><%= Name %></h1>

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

        <a href="/"><button>Home</button></a>
    </section>

    <script>
        // 检查是否存在有效食谱数据,存在则显示区块
        const hasRecipe = '<%= Name %>'.trim() !== '';
        if (hasRecipe) {
            document.querySelector('.GPT').style.display = 'block';
        }
    </script>
</body>

为什么之前的JS函数无效?

EJS代码是在服务端执行的,页面加载时目标区块的HTML已经生成完毕,前端JS无法回溯阻止服务端的渲染过程,只能控制DOM的显示状态。服务端条件渲染才是从根源上避免不必要的EJS代码执行。

内容的提问来源于stack exchange,提问作者Abhishek Prasad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 22:23:13