.append from Jquery loses me the lines and leaves everything followed


You see, I have a JSON with many records and I want to show it on a web page. To add it to an HTML use .append () Jquery.

It works well, it adds all the records and it takes well the styles and everything, but I see a behavior that I do not know how to solve.

When I retrieve a text with several paragraphs from the JSON, in HTML I get everything followed, with no new lines. When I inspect the paragraph, the lines look good on the console.

The piece of code is as follows:

success: function(json){
    var datos = JSON.parse(json);
    for(var i in datos) {
    $("#resultados").append('<div class="cuadro"> \
         <p><span class="negrita">Consulta</p> \
         <p>'+datos[i].pregunta+'</p> \
         <p class="negrita">Respuesta</p> \
         <p>'+ datos[i].respuesta+'</p></div>');

Do I have to pass some function to data [i] to get the lines out?

asked by monicapo 03.05.2018 в 09:31

2 answers


I'll put it in response so you do not get lost in the comments.

What you should do is:

respuesta = datos[i].respuesta; 
respuesta = respuesta.replace(/\n/g,"<br /><br />");

In javascript if you use the replace such that:

respuesta = respuesta.replace("\n","<br /><br />")

Only replaces the first occurrence, that is why you have to add / "Text to change" / g, because with this we indicate that we want you to capture all the "\ n" and replace them.

I hope it serves you.

answered by 03.05.2018 / 12:15

You must use <br> to make line breaks in html.

Your code would look like this:

success: function(json){
    var datos = JSON.parse(json);
    for(var i in datos) {
    $("#resultados").append('<div class="cuadro"><br>
         <p><span class="negrita">Consulta</p><br>
         <p class="negrita">Respuesta</p><br>
         <p>'+ datos[i].respuesta+'</p></div>');

The HTML line break item produces a line break in the text   (car return). It is useful to write a poem or an address,   where the division of the lines is significant.


answered by 03.05.2018 в 09:59