ajax、setRequestHeader()、Content-Type、application/x-www-form-urlencoded 和字符集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19694503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ajax, setRequestHeader(), Content-Type, application/x-www-form-urlencoded and charset
提问by Fernando Basso
I am having trouble understanding how to set the charset when the content type is not text/html, text/plain, or text/xml, but is application/x-www-form-urlencoded content type instead.
当内容类型不是 text/html、text/plain 或 text/xml,而是 application/x-www-form-urlencoded 内容类型时,我无法理解如何设置字符集。
Given this (simplified) javascript code:
鉴于这个(简化的)javascript代码:
var xhr = new XMLHttpRequest();
If I do notexplicitly set the encoding,
如果我没有明确设置编码,
xhr.open('POST', 'serv.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
firebug tells me that the content type is "application/x-www-form-urlencoded; charset=UTF-8."
firebug 告诉我内容类型是“application/x-www-form-urlencoded; charset= UTF-8”。
If I set the charset to ISO-8859-1 for instance,
例如,如果我将字符集设置为 ISO-8859-1,
xhr.open('POST', 'serv.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
firebug stilltells me "application/x-www-form-urlencoded; charset=UTF-8."
firebug仍然告诉我“application/x-www-form-urlencoded; charset= UTF-8”。
If I try something like
如果我尝试类似的东西
xhr.setRequestHeader('Content-Type', 'text/plain; charset=ISO-8859-1');
then it respects the charset.
然后它尊重字符集。
In all the cases the send() method goes like this:
在所有情况下,send() 方法都是这样的:
xhr.send('id=9&name=Yoda');
Why doesn't it honor the charset I specify if the Content-Type is x-www-form-urlencoded?
如果 Content-Type 是 x-www-form-urlencoded,为什么它不尊重我指定的字符集?
NOTE: I am using ISO-8859-1 just as an example. My goal is to understand what is going on.
注意:我使用 ISO-8859-1 作为示例。我的目标是了解正在发生的事情。
回答by aocole
The application/x-www-form-urlencodedmime type does not support parameters (such as charset). If you look at this sectionof the HTML5 spec, you will see how charset is determined (it's complicated). In particular, there is a note at the bottom of the section mentioning how charset cannot be specified as a parameter to the mime type.
的application/x-www-form-urlencodedmime类型不支持参数(如charset)。如果您查看HTML5 规范的这一部分,您将看到如何确定字符集(这很复杂)。特别是,本节底部有一个注释,提到了如何不能将字符集指定为 mime 类型的参数。

