如何將資料從 node.js 傳遞到本地 javascript,保持陣列功能?
const query = db.query(sql, post, (err, results) => {
if (err) {
throw err;
} else if (results.length >= 1) {
console.log(results);
const listResults = [];
for (let i = 0; i < results.length; i ) {
listResults.push(results[i].ENwords);
listResults.push(results[i].PLwords);
}
res.render('flashcards', {layout: 'flashcards', listResults});
在 flashcard.ejs 中:
<script>
let listWords = <%= listResults %>;
console.log(listWords);
</script>
我收到一個錯誤,串列中的第一項是“未定義”。
我也試過這個。這有效,但值不再是陣列:
<script>
let listWords = "<%= listResults %>";
console.log(listWords);
</script>
在這種特殊情況下,重新處理這些值是沒有意義的,因為不同的資料存盤在那里,不可能以適當的方式將它們劃分為一個新的串列。
uj5u.com熱心網友回復:
在 Node.js 中對陣列進行字串化
let listWords = <%- JSON.stringify(listResults) %>;
JSON.stringify 創建字串的 JSON 表示,并且 JSON 可用作陣列文字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/414724.html
標籤:
