AJAX explicitly set the encoding when sending out the post request

S

smartestdesign

I am trying to send request using ajax with some japanese text.
As any of you know XMLHttpRequest is send with utf-8.

I was hoping there is a way to send with different encoding like

var parameters = "metadata=" +
encodeURI(document.getElementById("metadata").value);

http_request.onreadystatechange = metadataUpdate;
http_request.open( 'POST', "/servlet/SendJapText", true );
http_request.setRequestHeader( "Content-type",
"application/x-www-form-urlencoded;charset=Shift-JIS" );
http_request.send( parameters );

Thanks in advance.
 
M

Martin Honnen

var parameters = "metadata=" +
encodeURI(document.getElementById("metadata").value);

I would suggest to use encodeURIComponent and not encodeURI (as the
value to be encoded could e.g. contain '=' or '&' meaning with encodeURI
you would get with value 'Kibo&Xibo'
metadata=Kibo&Xibo
while with encodeURIComponent you get
metadata=Kibo%26Xibo
).
http_request.onreadystatechange = metadataUpdate;
http_request.open( 'POST', "/servlet/SendJapText", true );
http_request.setRequestHeader( "Content-type",
"application/x-www-form-urlencoded;charset=Shift-JIS" );
http_request.send( parameters );

If you set the Content-Type request header it is up to your code to
ensure the argument you pass to the send method is properly encoded.
Thus if you want charset=Shift-JIS then you can't use encodeURI
respectively encodeURIComponent as those do not use/support Shift-JIS as
the charset, rather UTF-8.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top