Javascript和HTML:将文件保存为UTF-8而不使用BOM

时间:2010-10-22 02:27:53

标签: javascript html internet-explorer utf-8 utf-16

我正在尝试编写一个仅限MSIE的HTML页面(我称之为“标题页”),允许某人保存生成的HTML网页(我称之为“新页面”),只需单击一个按钮。

我发现显示的“另存为”对话框不允许将“新页面”保存为没有BOM的UTF-8。相反,它被保存为Unicode(UTF-8),而后者又让浏览器将其确定为UTF-16。以下是“标题页”的示例代码:

<html>
<head>
<script>

/** 
  *Takes the information in the form and arranges it in the proper format.
*/
function save()
{
str = "Hello World";            

mydoc = document.open();

mydoc.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");       
mydoc.write("\r\n\r\n");
mydoc.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n\t<head>\r\n\r\n\r\n\r\n\r\n<!--LOOK FOR \"EDIT HERE\"//-->\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\r\n\r\n<title>");

    /*Inserts str in the title*/
    mydoc.write(str);

    mydoc.write("</title>\r\n\r\n\t</head>\r\n\r\n\r\n\t<body>\r\n\r\n\r\n<!--EDIT HERE//-->\r\n\r\n<H1>");
    /*Inserts form variables from here*/
    mydoc.write(str);
    mydoc.write("</H1>\r\n\r\n\r\n<!--DO NOT EDIT BEYOND THIS POINT//-->\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n</body>\r\n</html>\r\n\r\n");

mydoc.execCommand("saveAs",true,"*.html");
mydoc.close();
}

</script>
</head>


<body>
<p align=right><input type="button" value="save" onclick="save()"></p>
</body>
</html>

我使用http://web-sniffer.net/检查了“新文件”,它告诉我“新文件”正在以这种方式保存:

<code>ÿþ!<�D�O�C�T�Y�P�E� �h�t�m�l� �P�U�B�L�I�C� �"�-�/�/�W�3�C�/�/�D�T�D� �X�H�T�M�L� �1�.�0 �T�r�a�n�s�i�t�i�o�n�a�l�/�/�E�N�"� �"�h�t�t�p�:�/�/�w�w�w�.�w�3�.�o�r�g�/�T…</code>

我有什么办法可以阻止它将“新页面”保存为UTF-16吗?或者它与代码无关?

此外,“另存为”对话框中有一个下拉列表,据说允许我更改字符编码,但真正做的就是保存“标题页”而不是“新页面”。

1 个答案:

答案 0 :(得分:1)

尝试将页面保存在其他编辑器中,例如Notepad ++,其中设置特定编码更加清晰:

http://download.cnet.com/Notepad/3000-2352_4-10327521.html