简体   繁体   English

定义JavaScript源文件的字符编码

[英]Defining the character encoding of a JavaScript source file

I would like to print a status message to my German users, which contains umlauts (ä/ü/ö). 我想向我的德国用户打印状态消息,其中包含变音符号(ä/ü/ö)。 I also would like them be in the source file rather than having to download and parse some extra file just for the messages. 我也希望他们在源文件中,而不是只为了消息下载和解析一些额外的文件。

However, I can't seem to find a way to define the encoding of a JS source file. 但是,我似乎无法找到一种方法来定义JS源文件的编码。 Is there something like HTML's http-equiv ? 是否有类似HTML的http-equiv Or should I define the encoding in the HTTP header? 或者我应该在HTTP标头中定义编码?

When I simply encode the file in UTF-8 an serve it, IE displays garbage. 当我简单地用UTF-8编码文件服务它时,IE显示垃圾。

Sending the encoding in the headers is always a good idea. 在头文件中发送编码总是一个好主意。

If that's not possible, the <script> tag has the charset property. 如果不可能, <script>标记具有charset属性。 W3C Reference W3C参考

<script src="translations.js" type="text/javascript" charset="utf-8"/>

似乎在HTML5中不推荐使用脚本标记的charset属性(仅对a和link标记不推荐使用它)。

While the charset parameter would seem helpful, it's important to note that it's actually deprecated in HTML5. 虽然charset参数似乎有用,但重要的是要注意它实际上已在HTML5中弃用。

http://www.w3.org/International/questions/qa-html-encoding-declarations#charset http://www.w3.org/International/questions/qa-html-encoding-declarations#charset

This might sound a bit dumb, but make sure you save your javascript file with the correct encoding in the editor you are using. 这可能听起来有点愚蠢,但请确保在您使用的编辑器中使用正确的编码保存您的javascript文件。 I had a problem with the encoding of my javascript file, and the solution was as simple as this! 我的javascript文件编码有问题,解决方案就像这样简单!

对于法语javascript js,我们使用了另一个字符集:

<script src="./js/MyScript.js" type="text/javascript" charset="iso-8859-1"></script>

The simplest solution to your problem would be to use unicode escape for special character in strings. 解决问题的最简单方法是对字符串中的特殊字符使用unicode转义。 This way, your code is not affected by the page that's hosting it. 这样,您的代码不会受托管它的页面的影响。

A tool that might help you: http://www.webstein.net/tools/javascript-unicode 一个可以帮助您的工具: http//www.webstein.net/tools/javascript-unicode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM