0

所以我正在制作一个应用程序,它需要将一个数组从服务器传递到客户端。我试过做

// 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>

这一直有效,直到我传递了一个包含 a 的数组,'无论如何我可以将数组传递到 javascript 中,但遇到某些章程的问题?

这是使用不和谐机器人来获取服务器并将它们显示在页面上。所以我想确保它可以显示所有字符。

如果我将'to"或 ` 更改为,它仍然可能导致某些输入出现问题。

谢谢。

4

1 回答 1

0

这就是@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)
于 2021-12-13T06:24:56.313 回答