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

问题描述

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

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



        <% 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

Ex: var getTest =<%= test%> ;;

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

Yes, you cant: if it is on server.

为什么:

EJS模板将在服务器上呈现Javscript开始执行(它将在浏览器上启动),因此无法返回到服务器并要求已经发送到浏览器的页面上的某些先前更改。



修改:此半数认为您在客户方使用EJS

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

上面的答案仍然可以使用,但是您需要在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).

对不起我自己没试过这个案子,但如果有人回答这个案子,我真的很期待

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

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

10-24 11:39