简体   繁体   中英

How to access index.js res property from an html script tag

i need an hand with the following access var problem.

I have two files, an index.js and a page.ejs, these needs me for a timer creation linked with datetimes rested in my local server.

//index.js..
    router.get('/mieiNoleggi', function(req,res,next){
        res.render("landMieiNoleggi",{title: 'miei noleggi', utente_loggato : req.session.utente, noleggi : req.session.mieiNoleggi, rimanenti : timer})
      })



//page.ejs

  <span id="d"><%- rimanenti.t_d %></span>
                                  <span id="h"><%- rimanenti.t_h %></span>
                                  <span id="m"><%- rimanenti.t_m %></span>
                                  <span id="s"><%- rimanenti.t_s %></span>
                                  
                         

                                  <script>
                                    a = rimanenti.t_s;
                                    document.getElementById("d").textContent = a ;
                                  </script>  

I can access res property 'rimanenti'(on index.js) with expression tags <%..%> in page.ejs, but if I want access it in script tag i cannot. I need to do it for activate the timers. someone knows how to accomplish this. pls

Within the <script> tags, you can use EJS expression tags only within Strings. Assuming the property rimanenti.t_s is defined, you can try this on your EJS page:

<script>
  a = parseInt("<%= rimanenti.t_s %>");
  // use Number() or parseFloat() if rimanenti.t_s is not meant to be an int
</script>

In the script tag also you need to embed the rimanenti.t_s value.

<script>
  a = <%= rimanenti.t_d %>;
  document.getElementById("d").textContent = a;
</script>

PS. Try to avoid using <%- instead of <%= in the HTML.
The first one is passing the unescaped value into the template, which can make some security issue in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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