我使用以下 Javascript 代码将文本区域保存到用户计算机上的文本文件中。这仅限于我们的内网,并且只允许使用 IE,因此仅限于安全性有限的 IE 并不是一个大问题;但是,我无法使用 php。因此,我想坚持使用 javascript 并调整以下脚本以强制字符集为 UTF-8。我在保存文件时注意到,它可以在记事本和 Notepad++ 中正确读取,但例如在写字板中打开时,很明显 UTF-16 不令人满意。同样,如果我将其保留在保存对话框中并手动将编码更改为 UTF-8,它将保存页面中的所有文本,而不仅仅是文本区域。另外,如果有人知道如何将默认的“保存类型”更改为文本 .txt,那就太好了,但并不重要。
<script type="text/javascript">
function SaveContentsTXT(element) {
if (typeof element == "string")
element = document.getElementById(element);
element3 = document.getElementsByName( 'TXTFILE' )[0];
if (element) {
if (document.execCommand) {
var oWin = window.open("about:blank", "_blank");
oWin.document.write((((element.value).replace(/ /g, ' ')).replace(/\t/g, ' ')).replace(/\n\r?/g, '<br />'));
oWin.document.close();
var success = oWin.document.execCommand('SaveAs', true, element3.value);
oWin.close();
if (!success)
alert("Sorry, your browser does not support this feature or you canceled.");
}
}
}
</script>
最佳答案
oWin.document.charset="UTF-8";
最终结果:
function SaveContentsTXT(element) {
if (typeof element == "string")
element = document.getElementById(element);
txtitle = document.getElementsByName( 'TXTFILE' )[0];
if (element) {
if (document.execCommand) {
var oWin = window.open("about:blank", "_blank");
oWin.document.write((((element.value).replace(/ /g, ' ')).replace(/\t/g, ' ')).replace(/\n\r?/g, '<br />'));
oWin.document.close();
oWin.document.save="text";
oWin.document.charset="UTF-8";
var success = oWin.document.execCommand('SaveAs', true, txtitle.value);
oWin.close();
if (!success)
alert("Sorry, your browser does not support this feature or you canceled.");
}
}
}
关于Javascript 将文本区域保存为 UTF-8 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9900140/