2017-05-27 64 views
0

我在这里遇到了一些问题。 IF条件内放置script标签。 Nah,script标记在条件为TRUE或FALSE时正在运行。如果在使用脚本标记的EJS中有条件不起作用

例如

<% if (info) { %> 
    <p><%=info%></p> 
      <script type="text/javascript"> 
      alert("Hi") 
      </script> 
    <% } %> 

结果:

IF = TRUE

alert("Hello world") 
<p>Hello world</p> 

IF = FALSE

alert("Hello world") 

段落属性在IF条件为TRUE时呈现。但script标记在IF条件为TRUE或FALSE时运行,我希望script标记像HTM​​L属性一样运行。

为什么会发生这种情况?谢谢

+0

这可能是类型相关的;在JavaScript中,'!!'FALSE'=== true' –

+0

所以我要用我的代码做什么?如果在EJS中有条件使用script标签是不可能的? @PaulS。 –

回答

0

好的,我回答我自己的问题。这是通过添加<% if (info.length > 0) { %>

解决由于我的路线文件中像这样

function isAuth(req, res, next){ 
    var token = req.session.token; 
    if(token){ 
     jwt.verify(token, 'jwtsecret', function(err, decoded){ 
      if(err){ 
       req.flash('info', err) 
       res.info = req.flash() 
       res.redirect('/login') 
       return; 
      } 
      req.decoded = decoded; 
      req.session.username = decoded.username 
      next(); 
     }) 
    } 
    else{ 
     req.flash('info', "Please login first") 
     res.redirect('/login') 
    } 
}; 

Router.get('/login', function(req, res){ 
    console.log(req.flash) 
    res.render('../views/login', {info : req.flash('info')}) 
}) 
<% if (info.length > 0) { %> 
    <script type="text/javascript"> 
    alert("Hello world") 
    </script> 
    <% } %>