I'm working with Spring and try to make a ajax call to @ResponseBody in my controller.
UPDATE
Okay, I added the changes I got told to to my ajax settings.
My param "jtSearchParam" still has the same encoding problem in IE.
+ I got an other error, 406, the response Header has the wrong content-type.
Here's my new code
Controller:
@RequestMapping(method = RequestMethod.POST, consumes="application/json; charset=utf-8", produces="application/json; charset=utf-8")
public @ResponseBody JSONObject getUsers(@RequestParam int jtStartIndex, @RequestParam int jtPageSize,
@RequestParam String jtSorting, @RequestParam String jtSearchParam,
HttpServletRequest request, HttpServletResponse response) throws JSONException{
Gson gson = new GsonBuilder()
.setExclusionStrategies(new UserExclusionStrategy())
.create();
List<User> users = userService.findUsers(jtStartIndex ,jtPageSize, jtSorting, jtSearchParam);
Type userListType = new TypeToken<List<User>>() {}.getType();
String usersJsonString = gson.toJson(users, userListType);
int totalRecordCount = userDao.getAmountOfRows(jtSearchParam);
usersJsonString = "{\"Message\":null,\"Result\":\"OK\",\"Records\":" + usersJsonString + ",\"TotalRecordCount\":" + totalRecordCount + "}";
JSONObject usersJsonObject = new JSONObject(usersJsonString);
return usersJsonObject;
}
So as you see I set the content type in produces
but that doesn't help.
If i debug the response header it looks like this:
(That causes an 406 Not Acceptable from the browser)
And my new ajax settings:
...
headers: {
Accept : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
contentType: "application/json; charset=utf-8",
mimeType:"application/json; charset=UTF-8",
cache:false,
type: 'POST',
dataType: 'json'
...
And my parameters still look the same in the IE!
Best Answer
Okay the problem with the json content-type can be solved like this:
With ResponseEntity you're able to change the content-type of the response header, that way ajax can interpret the json object the correct way and you wont get an 406 Http-error.
The problem with the encoding can be solved like this:
IE won't encode your "ü, ä, etc." correctly, it'll just add it to your URL like this:"jtSearchParam=wü" but it should actually look like that:"jtSearchParam=w%C3%BC" (If it doesn't you'll get the encoding errors on your serverside when you use IE)
So where ever you add certain values to your URL, make sure to use the JavaScript method
encodeURI
on that value before you actually add it to your URL Example:encodeURI(jtSearchParam)