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

519
Visualizações
Pass object to javascript function from ejs

I'm trying to attach a click event from my ejs file but I noticed that when my data coming from my database has a "newline", I get an error that says: Unexpected token in JSON at position 253

app.js

app.get('/', async (req, res) => {
   return res.render('page', {
      data: dataArray
   })
});

page.ejs:

  <% for(let t of data) { %>
  <tr class="tr-<%= t.id %>">
    <td><i class="fas fa-pencil-alt" onclick="editT('<%= JSON.stringify(t) %>')"></i>
    </td>
    <td><%= t.name %></td>
    <td><%= t.description %></td>
  </tr>
  <% } %>

script

function editT(t) {
  t = JSON.parse(t);
  console.log(t)
}

When a description has a "newline" and I use JSON.stringif(t) it comes broken:

let t = '{"id":1,"name":"Lorem","description":"Lorem Ipsum is simply dummy text of the printing and typesetting industry!

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum is simply dummy text of the printing and typesetting industry.
","created_at":"2022-04-18T22:19:00.153Z"}';


console.log(JSON.parse(treatment));

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

0

there two way of doing this without error

first one using <%- %> this way it will write the unescaped string

like this :

<td><i class="fas fa-pencil-alt" onclick="editT('<%- JSON.stringify(t)%>')"></i></td>

second one would be using encode

<td><i class="fas fa-pencil-alt" onclick="editT('<%= encodeURIComponent(JSON.stringify(t))%>')"></i></td>

the second one also requires you to do

function editT(t) {
  t = JSON.parse( decodeURIComponent(t));
  console.log(t)
}
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