
正文
ejs不能读取js变量??????
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
一、问题描述
用express搭了一个nodejs服务端,为了测试接口数据是否能够正常输出,用ejs作为模版引擎的html文件写js发请求。
1、请求正常,能在network看到,但是没有输出console的结果;
2、ejs不能读取异步js变量。
在服务端,html文件,如何将从接口fetch的数据渲染在ejs模版?
服务端A的html的js的ajax请求服务端A。
二、还原现场
下面介绍两种写法,title都可以拿到,但是在html请求的接口的数据无法正常传递给模版,导致页面无法渲染。
1、手动引入ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script src="ejs.min.js"></script>
<script type="text/template" id="J_tpl">
<% for(const i = 0; i < data.length; i++) { %>
<details>
<summary><%=data[i].names[0]%></summary>
<p>手机号:<%=data[i].phone%></p>
<p>性别:<%=data[i].sex%></p>
<p>部门:<%=data[i].department%></p>
</details>
<% } %>
</script>
<script type="text/javascript">
// 浏览器端,向服务端发请求。
fetch("/api/person/queryPerson", {
method: "POST",
headers: {
"Content-Type": "application/json"
}
})
.then(function(response) {
console.log(response, "响应");
return response.json();
})
.then(function(jsonData) {
// 1、没有打印console
console.log(jsonData, "返回数据");
const tpl = $("#J_tpl").html();
// 2、data在ejs读取不到
const html = ejs.render(tpl,{data: jsonData.data});
$("#J_dom").html(html);
})
.catch(function() {
console.log("出错了");
});
</script>
</head>
<body>
<h1>人员列表</h1>
<div id="J_dom"></div>
</body>
</html>
2、假设ejs能够读取js异步变量
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script type="text/javascript">
let globalData = [];
// 浏览器端,向服务端发请求。
fetch("/api/person/queryPerson", {
method: "POST",
headers: {
"Content-Type": "application/json"
}
})
.then(function(response) {
console.log(response, "响应");
return response.json();
})
.then(function(jsonData) {
// 1、没有打印console
console.log(jsonData, "返回数据"); // 2、data在ejs读取不到
globalData = jsonData.data;
})
.catch(function() {
console.log("出错了");
});
</script>
</head>
<body>
<h1>人员列表</h1>
<div id="J_dom">
<% for(const i = 0; i < globalData.length; i++) { %>
<details>
<summary><%=globalData[i].names[0]%></summary>
<p>手机号:<%=globalData[i].phone%></p>
<p>性别:<%=globalData[i].sex%></p>
<p>部门:<%=globalData[i].department%></p>
</details>
<% } %>
</div>
</body>
</html>
三、问题分析
1、在服务端,无法将js变量传给ejs变量。(待论证)
EJS模板将在服务器上呈现Javscript开始执行(它将在浏览器上启动),因此无法返回到服务器并要求已经发送到浏览器的页面上的某些先前更改。
四、解决方案






