javascript - 在 jQuery 中写入 ejs 变量

标签 javascript jquery node.js ejs

我正在使用 jQuery 将一些 html 附加到 div:

public/js/writeInputs.js

$("#myDiv").append("<input type='search' value='<%= filters.title %>' name='filters[title]' class='form-control'>")

在这种情况下,filters 是我从我的 node express 后端传递的一个对象,我想在我的输入中显示它的值。但是,上面将 ejs 变量呈现为字符串文字:

<%= filters.title %>

如果我将这个值硬编码到 html 中,它会按预期工作:

views/partials/inputs.ejs

<input type="search" name="filters[title]" value="<%= filters.title %>" class="form-control">

如何在 jQuery 中编写 ejs 变量?

我在我的附录中尝试了这些方法,但都没有用:

value="<%= filters.title %>"
value=${<%= filters.title %>}
value='"<%= filters.title %>"'

最佳答案

Node Express 首先呈现 HTML,然后浏览器基于 HTML 进行一些请求以获取脚本、图像等。因此 <%= filters.title %>不被 EJS 解释。

作为替代方案,将一些数据呈现为 HTML 并重写 JavaScript 以读取 filters.title来自 HTML,像这样:

<input type="hidden" id="filter" value="<%= filters.title %>" />

<script src="yourScript.js"></script>

yourScript.js:

    var filter = document.getElementById("filter").value;
    $("#myDiv").append("<input type='search' value='" + filter + "' name='filters[title]' class='form-control'>");

关于javascript - 在 jQuery 中写入 ejs 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56548995/

相关文章:

javascript - Tensorboard 未在 Google Chrome 中运行

javascript - 使用 Angular 循环遍历数组中的数组

jquery - 简单的jquery ajax请求语法错误

javascript - 在 node.js 中链接 underscore.js 抛出 'Invalid REPL keyword'

.net - SQL Server 数据库插入/更新 TCP 通知

node.js - 在 AWS Node socketcluster 上无法连接超过 1000 个连接

javascript - 如果我不使用 cognito,如何使用 Nodejs 在 axios 中准确签署 AWS elasticsearch 搜索请求?

javascript - 考虑到我的具体情况,是否有比 Array.map() 更高效地遍历 JSON 的方法?

html - 在ajax中用jquery更新css?

html - 在 Ajax 将数据插入 html 代码块后,格式化预 block 以删除第一个缩进?