首页 文章

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

提问于
浏览
9

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

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

var xhr = new XMLHttpRequest();

如果我 do not 明确设置编码,

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

firebug告诉我内容类型是“application / x-www-form-urlencoded; charset = 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');

firebug still 告诉我“application / x-www-form-urlencoded; charset = UTF-8 . ”

如果我尝试类似的东西

xhr.setRequestHeader('Content-Type', 'text/plain; charset=ISO-8859-1');

然后它尊重charset .

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

xhr.send('id=9&name=Yoda');

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

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

1 回答

  • 12

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

相关问题