如何使用 ejs 在 javascript 中从 node.js 访问数组
How can I acess a array from node.js in javacsript with ejs
所以我正在制作一个应用程序,它需要将数组从服务器传递到客户端。我试过了
// Server
app.get('/', (req,res) => {
res.render('index', {
data: ["Hello"]
})
})
// EJS
<script>
const data = '<%- JSON.stringify(locals.data) || [] %>'
</script>
但是它不是 ejs 中的数组所以我尝试了
// Server
app.get('/', (req,res) => {
res.render('index', {
data: ["Hello"]
})
})
// EJS
<script>
const data = JSON.parse('<%- JSON.stringify(locals.data) || [] %>')
</script>
在我传递一个包含 '
的数组之前一直有效,无论如何我可以将数组传递到 javascript 并在某些章程中遇到问题吗?
这正在与 discord 机器人合作,以获取服务器并将它们显示在页面上。所以我想确保它可以显示所有字符。
如果我将 '
更改为 "
或 ` 它仍然可能导致某些输入出现问题。
谢谢。
@hacKaTun3s 的回答:
const data = <%- JSON.stringify(locals.data) || [] %>
但这会导致语法错误并且很烦人,所以我正在使用这个:
EJS:
<p hidden id=scrpt_get_locals><%= JSON.stringify(locals) %></p>
它将被隐藏,我们将在脚本中访问它的内容。
JAVASCRIPT:(推迟)
const locals = JSON.parse(document.getElementById('scrpt_get_locals').innerText) // Get element text that has locals, then parse it
document.getElementById('scrpt_get_locals').innerText = '' // Remove the text (So we don't have a random element with the locals
document.getElementById('scrpt_get_locals').id = '' // Remove id (Optional)
编辑:
顶部访问您将要访问的变量数据:
console.log(locals.data)
所以我正在制作一个应用程序,它需要将数组从服务器传递到客户端。我试过了
// Server
app.get('/', (req,res) => {
res.render('index', {
data: ["Hello"]
})
})
// EJS
<script>
const data = '<%- JSON.stringify(locals.data) || [] %>'
</script>
但是它不是 ejs 中的数组所以我尝试了
// Server
app.get('/', (req,res) => {
res.render('index', {
data: ["Hello"]
})
})
// EJS
<script>
const data = JSON.parse('<%- JSON.stringify(locals.data) || [] %>')
</script>
在我传递一个包含 '
的数组之前一直有效,无论如何我可以将数组传递到 javascript 并在某些章程中遇到问题吗?
这正在与 discord 机器人合作,以获取服务器并将它们显示在页面上。所以我想确保它可以显示所有字符。
如果我将 '
更改为 "
或 ` 它仍然可能导致某些输入出现问题。
谢谢。
@hacKaTun3s 的回答:
const data = <%- JSON.stringify(locals.data) || [] %>
但这会导致语法错误并且很烦人,所以我正在使用这个:
EJS:
<p hidden id=scrpt_get_locals><%= JSON.stringify(locals) %></p>
它将被隐藏,我们将在脚本中访问它的内容。
JAVASCRIPT:(推迟)
const locals = JSON.parse(document.getElementById('scrpt_get_locals').innerText) // Get element text that has locals, then parse it
document.getElementById('scrpt_get_locals').innerText = '' // Remove the text (So we don't have a random element with the locals
document.getElementById('scrpt_get_locals').id = '' // Remove id (Optional)
编辑:
顶部访问您将要访问的变量数据:
console.log(locals.data)