Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

247
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda