【问题标题】:Impossible to set a custom encoding when post trough XMLHTTPRequest通过 XMLHTTPRequest 发布时无法设置自定义编码
【发布时间】:2013-12-28 09:21:42
【问题描述】:

来自上一版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"

奇怪...

【问题讨论】:

    标签: javascript ajax encoding utf-8 xmlhttprequest


    【解决方案1】:

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

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

    【讨论】:

    • 在 OP 的问题中也可以看到这个解决方法:stackoverflow.com/questions/2283829/…
    • 我没有从规范中读到这个。如果您参考页面上的几个示例,它们会明确描述字符集:client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    猜你喜欢
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多