10

当内容类型不是 text/html、text/plain 或 text/xml,而是 application/x-www-form-urlencoded 内容类型时,我无法理解如何设置字符集。

鉴于这个(简化的)javascript代码:

var xhr = new XMLHttpRequest();

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

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

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

如果我尝试类似

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

然后它尊重字符集。

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

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

如果 Content-Type 是 x-www-form-urlencoded,为什么它不遵守我指定的字符集?

注意:我以 ISO-8859-1 为例。我的目标是了解发生了什么。

4

2 回答 2

12

The application/x-www-form-urlencoded mime type does not support parameters (such as charset). If you look at this section of 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.

于 2014-06-25T17:48:46.917 回答
0

你可以试试这段代码:

.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
于 2022-01-28T07:58:16.467 回答