一、問題描述
用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開始執行(它將在瀏覽器上啟動),因此無法返回到服務器並要求已經發送到瀏覽器的頁面上的某些先前更改。
四、解決方案