js 脚本可以在同一文件中的 EJS 上下文/页面中获取写入的变量吗 [英] Can a js script get a variable written in a EJS context/page within the same file

查看:18
本文介绍了js 脚本可以在同一文件中的 EJS 上下文/页面中获取写入的变量吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我在标题中写的,我想从写入 ejs 页面/文件的变量中获取值,从同一页面内的 javascript 文件中获取值

As I wrote in the title, I'd like to get a value from a variable written into a ejs page/file, from a javascript file within the same page

EJS:

<% var test = 101; %>

JS:

<script>
    var getTest = test;
</script>

或者,如果我想使用写入 EJS 文件的函数(带参数)并在 JS 上下文中使用此函数,其中参数从 JS 上下文提供给函数,该怎么办

Or what if I'd like to use a function (with parameter) written into a EJS file and use this function in a JS context where the parameter is given to the function from JS context

EJS:

<% function fn(par){ ... } %>

JS:

<script>
   var test = 101;
   <%>fn(test)<%> 
</script>

推荐答案

编辑:这半认为你在服务器端使用EJS

Edit: this Half considers you are using EJS on server side

1) 您可以将 ejs 变量值传递给 Javascript 变量

1) You can pass an ejs variable value to a Javascript variable

        <% var test = 101; %> // variable created by ejs
        <script>
           var getTest = <%= test  %>;  //var test is now assigned to getTest which will only work on browsers
           console.log(getTest);  // successfully prints 101 on browser
        </script>

只需创建一个 ejs 变量并将脚本标记内的值分配给 var getTest

simply create an ejs variable and assign the value inside the script tag to the var getTest

例如:var getTest = <%= test %>;

2) 您不能将 javascript 变量值传递给 ejs 变量

2) You can't pass an javascript variable value to a ejs variable

是的,你不能:如果它在服务器上.

Yes, you cant: if it is on server.

为什么:

EJS 模板将在 Javscript 开始执行之前呈现在服务器上(它将在浏览器上启动),因此无法返回服务器并要求页面上的一些先前更改已经发送到浏览器.<小时>编辑:这一部分认为您在客户端

The EJS template will be rendered on the server before the Javscript is started execution(it will start on browser), so there is no way going back to server and ask for some previous changes on the page which is already sent to the browser.


Edit: this Half considers you are using EJS on Client side

3) 如果 EJS 在客户端,则将 EJS 变量传递给 javascript

3) if EJS is on client side, and pass EJS variable to javascript

上面的答案仍然有效,但您需要在 EJS 模板中加载脚本,而不是在模板呈现之前加载的脚本(在这种情况下当然不会是有效的 javascript).

The answer above will still work, but you will require to load the script within the EJS template, not the script loaded before the template rendered(in that case it will of-course no be a valid javascript).

4) 如果 EJS 在客户端,则将 javascript 变量传递给 EJS

4) if EJS is on client side, and pass javascript variable to EJS

很抱歉我自己没有尝试过这个案例,但我真的很期待有人回答这个案例

I m sorry I have myself not tried this case, but I really look forward if someone answers this case

这篇关于js 脚本可以在同一文件中的 EJS 上下文/页面中获取写入的变量吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆