Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

javascript - Can a js script get a variable written in a EJS context/page within the same file

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>

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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>

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

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

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

Yes, you cant: if it is on server.

Why:

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) if EJS is on client side, and pass EJS variable to 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) 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...