【问题标题】:Javascript to save textarea to file as UTF-8Javascript将文本区域保存为UTF-8文件
【发布时间】:2012-04-11 14:38:42
【问题描述】:

我正在使用以下 Javascript 代码将文本区域保存到用户机器上的文本文件中。这仅限于我们的 Intranet,并且只允许使用 IE,因此仅限于安全性有限的 IE 并不是一个大问题;但是,我无法使用 php。因此,我想坚持使用 javascript 并调整以下脚本以强制字符集为 UTF-8。保存文件时我注意到它可以在记事本和记事本++中正确读取,但是例如在写字板中打开时,很明显 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, '&nbsp;')).replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')).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>

【问题讨论】:

  • 最好能说明您的目标是哪个 IE 版本。
  • 关于字符集,我不知道,但是根据what seems to be the reference,文件的默认名称是execCommand()的第三个参数。这不是element3 的目标吗?
  • @Stock Overflaw "element" 是我要保存的文本区域,element3.value 是我将 element.value 保存为的论坛字段输入值。它按原样工作,直到我更改编码。不过,我明白你的意思。嗯

标签: javascript internet-explorer textarea


【解决方案1】:
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, '&nbsp;')).replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')).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.");         
            }   
        } 
    } 

【讨论】:

    猜你喜欢
    • 2013-04-23
    • 1970-01-01
    • 2012-12-31
    • 2014-02-11
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多