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.
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)