通过XMLHTTPRequest发布时无法设置自定义编码

时间:2013-12-10 17:45:18

标签: javascript ajax encoding utf-8 xmlhttprequest

从上一版Chrome浏览器的JS控制台:

x = new XMLHttpRequest();
x.open('POST', '?a=2');
x.setRequestHeader('Content-Type', 
                   'application/x-www-form-urlencoded; charset="ISO-8859-1"');
x.send({b:2});

请求以错误的编码发送,在网络检查器中,我看到:

Content-Type:application/x-www-form-urlencoded; charset="UTF-8"

另一个非常奇怪的行为,当我提供charset=ISO-8859-1代替charset="ISO-8859-1"时,我得到:

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

因为两者之间发生了变化。


编辑2013/12/11

嗯,对我来说真正错误的一点是,如果您不发送(数据),编码更改将按预期工作。这需要我之前的例子(注意最后一行的变化):

x = new XMLHttpRequest();
x.open('POST', '?a=2');
x.setRequestHeader('Content-Type', 
                   'application/x-www-form-urlencoded; charset="ISO-8859-1"');
x.send();

然后网络正确输出:

Content-Type:application/x-www-form-urlencoded; charset="ISO-8859-1"

...奇怪

1 个答案:

答案 0 :(得分:2)

W3C XMLHttpRequest specification表示字符集始终为UTF-8,指定另一个字符集不会强制浏览器更改编码。

请注意,jQuery的$ .ajax方法的documentation在设置Content-Type时说的完全相同