سؤال

I am trying to display the contents of a text file into a text area element but the am having issues with a line break being displayed as '\n' instead of actually doing it.

<textarea id = "textArea" name = "textArea" data-ng-model="note.text"></textarea>

javascript to add the text to text area element

var $promise=$http.post("http://localhost/PHP/findNotes.php", data); //send data to user.php
$promise.then(function(msg){

       document.getElementById("textArea").value = msg.data;

      });

PHP file to get file contents

$note=json_decode(file_get_contents('php://input'));  //get note 
$noteId = ($note->noteId);  
$userId = ($note->userId); 

$filename = 'file://localhost/Library/WebServer/Documents/Notes/'.$userId.'/'.$noteId.'.txt';

if (file_exists($filename))   
{  
  $file = fopen($filename, "r");  
  while (!feof($file))   
  {  
    $display = fgets($file, filesize($filename));  
    echo $display; 
  }  
  fclose($file);  
}   
else   
{  
  echo "Error occurred!";  
} 

When reading the file with content

line1\nline2\n\nline4

the exact same thing is shown in the text area

However if the file contents is applied directly to the textarea in the js code then the linebreaks work perfectly.

so if the JS is changed to

document.getElementById("textArea").value ="line1\nline2\n\nline4";

then the output in the text area is correctly:

line1
line2

line4

Would appreciate any help, it seems as if it's a problem with the format of the text received from PHP? Thanks in advance

هل كانت مفيدة؟

المحلول

You need to escape the \n character for ajax to \\n

So before you echo $display in findNotes.php you should insert:

$display=str_replace("\n", "\\n", $display);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top