我正在尝试将文本文件的内容显示到文本区域元素中,但遇到换行符显示为“\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 代码中的文本区域,则换行符可以正常工作。
那么如果JS改成
document.getElementById("textArea").value ="line1\nline2\n\nline4";
那么文本区域的输出是正确的:
line1
line2
line4
希望得到任何帮助,似乎是从 PHP 接收的文本格式有问题? 提前致谢
最佳答案
您需要将 ajax 的\n 字符转义为\\n
因此,在 findNotes.php 中 echo $display 之前,您应该插入:
$display=str_replace("\n", "\\n", $display);
关于javascript - 在 html 文本区域中显示文件内容时出现换行问题 - javascript PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22426718/