简体   繁体   English

如何在 ejs 视图中作为 ejs 变量访问 js 变量(在脚本标签内)

[英]How to access js variable (within script tag) in ejs view as ejs variable

I have a script in order to get the selected option of a select tag in my ejs view, this is in order to dynamically set the value of the name attribute to the selected option.我有一个脚本,用于在我的 ejs 视图中获取选择标记的选定选项,这是为了将 name 属性的值动态设置为选定选项。 I then use the name of this input tag in my nodeJS server-side.然后我在我的 nodeJS 服务器端使用这个输入标签的名称。 However, I receive ReferenceError: p is not defined .但是,我收到ReferenceError: p is not defined

What is the correct way to access the JS variable in my ejs view?在我的 ejs 视图中访问 JS 变量的正确方法是什么?

EJS EJS

<select>
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>

<!-- JS as a tag in the EJS !-->
<script>
let p = document.querySelector('select').selectedOptions[0].value;
</script>

<input type="file" name="<%= p %>">

Any help much appreciated.非常感谢任何帮助。 Thank you.谢谢你。

EJS code is executed on the the server and JS code is executed on the browser. EJS 代码在服务器上执行,JS 代码在浏览器上执行。

The only way to have EJS access your DOM variable is if there was a call to the backend API via JS code and then have that evaluated and returned to frontend, but this is a poor design and is not recommended.让 EJS 访问您的 DOM 变量的唯一方法是通过 JS 代码调用后端 API,然后对其进行评估并返回到前端,但这是一个糟糕的设计,不推荐。

Its better you handle the the value of tag via JS only, the details will be sent to sever on form submission.最好仅通过 JS 处理标签的值,详细信息将在表单提交时发送到服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM