我的服务器文件:
router.get('/', function (req, res, next) {
res.render('chat', {user: req.user, message: null});
});
我的客户档案:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/> <link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="style.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script> <title>Simple Chat App</title> </head> <body> <header> <h1>Super Chat</h1> </header> <section> <div id="change_username"> <input id="username" type="text"/> <button id="send_username" type="button">Change username</button> </div> </section> <section id="chatroom"> <section id="feedback"></section> </section> <section id="input_zone"> <input id="message" class="vertical-align" type="text"/> <button id="send_message" class="vertical-align" type="button">Send</button> </section> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> <% var user = <% user %> %> console.log(user); </script> <script src="chat.js"></script> </body> </html>
我收到一个错误:
Could not find matching close tag for "<%".
我该如何解决?
<% var user = <% user %> %>
您不能嵌套<% %>
块。您处于EJS模式之内还是之外。您无法进入Extra Deep EJS模式。
此外,您也不能只将变量输出到客户端JS。您需要从该变量生成JavaScript源代码。JSON.stringify
是从对象,数组和字符串生成对象,数组和字符串文字的好方法。
<script> const user = <%- JSON.stringify(user); %> console.log(user); </script>
请注意,使用<%-
进行输出时不会转义HTML。
var user = "<%=user%>" // Please change this line
更新的代码
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/> <link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="style.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script> <title>Simple Chat App</title> </head> <body> <header> <h1>Super Chat</h1> </header> <section> <div id="change_username"> <input id="username" type="text"/> <button id="send_username" type="button">Change username</button> </div> </section> <section id="chatroom"> <section id="feedback"></section> </section> <section id="input_zone"> <input id="message" class="vertical-align" type="text"/> <button id="send_message" class="vertical-align" type="button">Send</button> </section> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> var user = "<%= user %>" // problem is here console.log(user); </script> <script src="chat.js"></script> </body> </html>
希望对您有帮助。
<script type="text/javascript">
var user = '<%= user %>'
console.log(user);
</script>
尝试一下。祝好运。 :)
使用var user = <%- `${user}` %>
user
是您要传递给模板的唯一变量,因此仅应将其放置在<%- %>
中。并且由于它必须是有效的javascript表达式,因此请使用模板文字。
<%
'Scriptlet'标签,用于控制流,无输出<%=
将值输出到模板中(转义HTML)<%-
将未转义的值输出到模板中