ajax,setRequestHeader(),Content-Type,application/x-www-form-urlencoded和charset

Fer*_*sso 10 javascript ajax character-encoding

当内容类型不是text/html,text/plain或text/xml时,我无法理解如何设置charset,而是app/x-www-form-urlencoded内容类型.

给出这个(简化的)javascript代码:

var xhr = new XMLHttpRequest();
Run Code Online (Sandbox Code Playgroud)

如果我没有明确设置编码,

xhr.open('POST', 'serv.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Run Code Online (Sandbox Code Playgroud)

萤火告诉我,内容类型是"应用程序/ X WWW的窗体-urlencoded;字符集= UTF-8 ".

例如,如果我将charset设置为ISO-8859-1,

xhr.open('POST', 'serv.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
Run Code Online (Sandbox Code Playgroud)

firebug 仍然告诉我"application/x-www-form-urlencoded; charset = UTF-8."

如果我尝试类似的东西

xhr.setRequestHeader('Content-Type', 'text/plain; charset=ISO-8859-1');
Run Code Online (Sandbox Code Playgroud)

然后它尊重charset.

在所有情况下,send()方法如下所示:

xhr.send('id=9&name=Yoda');
Run Code Online (Sandbox Code Playgroud)

如果Content-Type是x-www-form-urlencoded,为什么不尊重我指定的charset?

注意:我正在使用ISO-8859-1作为示例.我的目标是了解正在发生的事情.

小智 12

application/x-www-form-urlencodedmime类型不支持参数(如charset).如果您查看HTML5规范的这一部分,您将看到如何确定字符集(它很复杂).特别是,在该部分的底部有一个注释,提到如何将charset指定为mime类型的参数.