在html文本区域中显示文件内容时的换行问题 - javascript PHP

时间:2014-03-15 16:47:24

标签: javascript php textarea line-breaks

我正在尝试将文本文件的内容显示到文本区域元素中,但是我遇到的问题是换行符显示为' \ n'而不是真正做到这一点。

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

javascript将文本添加到文本区域元素

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文件

$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!";  
} 

阅读内容

的文件时
line1\nline2\n\nline4

文本区域中显示完全相同的内容

但是,如果文件内容直接应用于js代码中的textarea,则换行符可以正常工作。

所以如果JS改为

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

然后文本区域中的输出正确:

line1
line2

line4

感谢任何帮助,似乎从PHP收到的文本格式有问题吗? 提前致谢

1 个答案:

答案 0 :(得分:3)

您需要将aj字符的\ n字符转义为\\ n

因此,在回显findNotes.php中的$ display之前,您应该插入:

$display=str_replace("\n", "\\n", $display);
相关问题