Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

240
Visualizações
How can I acess a array from node.js in javacsript with ejs

So I am making a app where it needs to pass an array from the server into the client. I have tried to do

// Server
app.get('/', (req,res) => {
  res.render('index', {
    data: ["Hello"]
  })
})

// EJS
<script>
  const data = '<%- JSON.stringify(locals.data) || [] %>'
</script>

But then its not an array in the ejs so I tried

// Server
app.get('/', (req,res) => {
  res.render('index', {
    data: ["Hello"]
  })
})

// EJS
<script>
  const data = JSON.parse('<%- JSON.stringify(locals.data) || [] %>')
</script>

That worked until I passed an array with a ' in it, is there anyway that I can pass the array into javascript with having problems with having certain charters?

This is working with a discord bot to get the servers and display them on a page. So I want to make sure it can show all the charaters.

And if I change the ' to " or ` it could still cause issues with some inputs.

Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Thats to @hacKaTun3s for this answer:

const data = <%- JSON.stringify(locals.data) || [] %>

But this causes sytax errors and can be annoying, so i am using this:

EJS:

<p hidden id=scrpt_get_locals><%= JSON.stringify(locals) %></p>

It will be hidden and in the script we will access its contents.

JAVASCRIPT: (DEFER)

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)

Edit:

Top access the variable data you would:

console.log(locals.data)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda