简体   繁体   中英

Posting JSON via AJAX accentuation problems

I'm having bad times when posting JSON via AJAX.

For testing purposes , the code below reproduces the problem, and was created in the Firefox Scratchpad (I'm using Backbone in the application layer):

var xhr = new XMLHttpRequest();
xhr.open("POST", "/my/api/url"); // could be PUT too
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({ test: "é" }));

Actually, no matter what accented string I use in my JSON, it's always sent incorrectly (I've tested in Firefox and Chrome, both latest versions) - I can see the request data wrong in Chrome DevTools/Firebug. What is sent in this case is é .

I have found an workaround in Java. I would not bother using it once or twice, however, seems like this is not going to be the case. There are still lots of stuff to do.
The workaround is the following:

test = new String(test.getBytes("ISO-8859-1"), "UTF-8");

Any further help would be appreciated.

My setup (if anyone needs):

  • Windows 7 x64
  • JDK 1.7 x64
  • JBoss 4.2.3
  • RESTEasy
  • MyEclipse 9.1

I'll be often updating this question with interesting data whenever they appear.

You are not passing the json properly

xhr.send(JSON.stringify({ test: "é" }));

also there should be qoutes for key like this { "test": "e" }

you can use variable

var jsonStr={ "test": "é" };
xhr.send(JSON.stringify(jsonStr));

I don't think you need to stringify json since you have set Content-Type to json, not sure about it though.

Hope it helped you...

Try sending the parameters this way

var params='json='+jsonStr;
xhr.send(params);

I've resolved my own problem. As I am using RESTEasy, one of my methods were using an interceptor MessageBodyReader . In this class, I was reading the body without using the request's encoding...

Was:

String body = new String(IOUtils.toByteArray(inputStream));

Become:

String body = new String(IOUtils.toByteArray(inputStream), request.getCharacterEncoding());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM