按下按钮后显示来自 javascript 变量的数据
Display data from javascript variable after a button is pressed
使用 express.js
,假设您在 ejs
文件中嵌入了以下 javascript 变量:<%= someVariable %>
如果实际值将从页面上的表单中获取,那么您将如何在同一页面上显示此变量的值(例如在 bootstrap 模式元素 https://getbootstrap.com/docs/4.0/components/modal/ 中) ,在页面已经像这样加载之后:
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" id="someVariable" name="someVariable" type="text" placeholder="Enter Value" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="button" id="search" data-toggle="modal" data-target="#modal">Search</button>
</form>
我 运行 遇到的问题是因为变量是未定义的,在将值输入表单之前,每当我尝试加载页面时都会收到以下错误:someVariable is not defined
有没有办法在变量 someVariable
未定义时加载此页面?
locals 对象包含您传入的所有 ejs 值。在使用 someVariable
之前,您可以使用简单的 if 语句检查它是否已定义:
<% if (locals.someVariable) { %>
<h1><%= someVariable %></h1>
<% } %>
使用 express.js
,假设您在 ejs
文件中嵌入了以下 javascript 变量:<%= someVariable %>
如果实际值将从页面上的表单中获取,那么您将如何在同一页面上显示此变量的值(例如在 bootstrap 模式元素 https://getbootstrap.com/docs/4.0/components/modal/ 中) ,在页面已经像这样加载之后:
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" id="someVariable" name="someVariable" type="text" placeholder="Enter Value" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="button" id="search" data-toggle="modal" data-target="#modal">Search</button>
</form>
我 运行 遇到的问题是因为变量是未定义的,在将值输入表单之前,每当我尝试加载页面时都会收到以下错误:someVariable is not defined
有没有办法在变量 someVariable
未定义时加载此页面?
locals 对象包含您传入的所有 ejs 值。在使用 someVariable
之前,您可以使用简单的 if 语句检查它是否已定义:
<% if (locals.someVariable) { %>
<h1><%= someVariable %></h1>
<% } %>