我有一个HTML文件使用Javascript通过ActiveXObject在.txt文件上执行文件I / O操作( only 在Internet Explorer中,在Windows操作系统上工作) 。
HTML页面上有一个文本输入框和一个按钮。该按钮调用函数onclick
以将输入的文本写入.txt文件的末尾。 HTML页面上还有一个textarea,其中.txt文件的修改内容被复制并粘贴到其中。到目前为止所有这一切都在起作用......
var newText = oldText + "\n" + document.getElementById("userInput").value;
当然,转义字符\n
适用于HTML页面,而不适用于.txt文件...
escape()
值found here和ANSI
值found here上使用ASCII
方法,但没有运气。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
</head>
<body>
<p>
Enter some text here:
<input type = "text" id = "userInput" />
</p>
<input type = "button" value = "submit" onclick = "main();" />
<br />
<hr />
<br /><br /><br />
<textarea id = "textHere" rows = 25 cols = 150></textarea>
<script type = "text/javascript">
// executes all code from this function to prevent global variables
function main()
{
var filePath = getThisFilePath();
var fileText = readFile(filePath);
writeFile(filePath, fileText);
} // end of function main
function getThisFilePath()
{
var path = document.location.pathname;
// getting rid of the first forward-slash, and ending at the last forward-slash to get rid of file-name
var correctPath = path.substr(1, path.lastIndexOf("/") );
var fixedPath = correctPath.replace(/%20/gi, " "); // replacing all space entities
return fixedPath;
} // end of function getThisFilePath
function readFile(folder)
{
var fso = "";
var ots = "";
var oldText = "";
try
{
fso = new ActiveXObject("Scripting.FileSystemObject");
// in the same folder as this HTML file, in "read" mode (1)
ots = fso.OpenTextFile(folder + "writeToText.txt", 1, true);
oldText = ots.ReadAll();
ots = null;
fso = null;
}
catch(e)
{
alert("There is an error in this code!\n\tError: " + e.message);
exit(); // end the program if there is an error
}
return oldText;
} // end of function readFile
function writeFile(folder, oldText)
{
var fso = "";
var ots = "";
var newText = oldText + "\n" + document.getElementById("userInput").value;
try
{
fso = new ActiveXObject("Scripting.FileSystemObject");
// in the same folder as this HTML file, in "write" mode (2)
ots = fso.OpenTextFile(folder + "writeToText.txt", 2, true);
ots.Write(newText);
ots.Close();
ots = null;
fso = null;
}
catch(e)
{
alert("There is an error in this code!\n\tError: " + e.message);
exit(); // end the program if there is an error
}
setText(newText); // with the function below
} // end of function writeFile
// called from the function writeFile
function setText(textFile)
{
document.getElementById("textHere").value = textFile;
} // end of function setText
</script> <!-- end of javascript -->
</body>
</html>
答案 0 :(得分:2)
Windows期望"\r\n"
作为换行符。我很确定你会在你的textarea value
中找到它们(在击中后)。当您使用"\n"
设置值时,它们将自动插入,并且大多数库(如jQuery)在读取值时会使用“正常”换行符替换它们。
但是,我希望只有"\n"
的文件读/写才能工作,当你将文件的文本加载到textarea中时,它们应该显示出来。 MS Notepad可能无法显示它们。