-3

I have a php file test.php

<!DOCTYPE html>
<html>
<head>
 <script src="/jquery.js"> </script>
 <script>
 $(document).ready(function(){
$.post("/text.php",function(result){ $("body").append(result);});
 });
</script>
</head>
 <body>
</body>
</html>

text.php

hello
far

faar


faar

We know In html, All line breaks and spaces , automatically reduced to single space ,But in this case line breaks increasing the space between wordsenter image description here

Any ideas ? please

beginner
  • 2,366
  • 4
  • 29
  • 53

4 Answers4

1

Check the Content-Type header in the network history.

I assume for the text.php it's text/plain, where line breaks are relevant. That's ignored in the first test as the text is appended into HTML DOM.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
1

What you receive from the Ajax call is just plain text. If you append a plain text with jQuery, it will be added as a text node.

You can explicitly turn the plain text to HTML.

 $(document).ready(function(){
   $.post("/text.php",function(result){
     $("body").append($(result));      // Notice the $ before result
   });
 });

Or you can wrap your text in a p or span element.

 $(document).ready(function(){
   $.post("/text.php",function(result){
     $("body").append($("<p>" + result + "</p>"));      // Notice the $ before result
   });
 });
Gokhan Kurt
  • 8,239
  • 1
  • 27
  • 51
0

try this If you want to remove multiple spaces from result

$(document).ready(function(){
   $.post("/text.php",function(result){ result=result.replace(/\s+/g, ' '); $("body").append(result);});
});

And try this if you want to keep those as multiple line as it was in text.php

function nl2br(str, is_xhtml) {
     var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
     return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}    
$(document).ready(function(){
   $.post("/text.php",function(result){ result=nl2br(result); $("body").append(result);});
});
Rakesh Sojitra
  • 3,538
  • 2
  • 17
  • 34
0

Why don't use trim/rtril or ltrim php function? and for line break see here

Community
  • 1
  • 1
YannickIngenierie
  • 602
  • 1
  • 13
  • 37