Impossible to set a custom encoding when post trou

2019-05-26 07:09发布

问题:

From the JS console of the last version of chrome browser :

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});

The request is sent with the wrong encoding, in the network inspector, I see :

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

Another pretty strange behavior, when i provide charset=ISO-8859-1 instead of charset="ISO-8859-1", I get :

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

As something had change in between.


Edit 2013/12/11

Well, the point that is really buggy for me is that if you do not send (data), the encoding change works as expected. It take my previous example (note the change on the last line) :

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

Then the network correctly output :

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

Strange...

回答1:

The W3C XMLHttpRequest specification dictates that the charset is always UTF-8, specifying another charset will not force the browser to change the encoding.

Note that the documentation for jQuery's $.ajax method says the exact same thing when it comes to setting the Content-Type