ajax, setRequestHeader(), Content-Type, application/x-www-fo

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

本文关键字:application x-www-fo Content-Type setRequestHeader ajax      更新时间:2023-09-26

我无法理解如何在内容类型不是 text/html、text/plain 或 text/xml,而是 application/x-www-form-urlencoding 内容类型。

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

var xhr = new XMLHttpRequest();

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

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

萤火虫告诉我内容类型为"application/x-www-form-urlencoded;字符集=UTF-8

例如,如果我将字符集设置为 ISO-8859-1,

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

Firebug仍然告诉我"application/x-www-form-urlencoded;字符集=UTF-8

如果我尝试类似的东西

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

然后它尊重字符集。

在所有情况下,send() 方法都是这样的:

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

如果内容类型是 x-www-form-urlencoded,为什么它不接受我指定的字符集?

注意:我仅以 ISO-8859-1 为例。我的目标是了解正在发生的事情。

application/x-www-form-urlencoded mime 类型不支持参数(如 charset )。如果你看一下HTML5规范的这一部分,你会看到字符集是如何确定的(这很复杂)。特别是,本节底部有一个注释,提到如何不能将字符集指定为 mime 类型的参数。

您可以尝试以下代码:

.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');