I have a web page that requests an hebrew string using Ajax but the string is returned as '??????'
The weird thing is that when inserting that same string to the page using JSTL and not Ajax, it is shown correctly...
In my web page I'm declaring
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
That's my controller:
@RequestMapping("get_label")
public @ResponseBody String getLabel()
{
String str = "בדיקה";
return str;
}
And my ajax request:
$.ajax({
url: "get_label",
success: function(result)
{
alert(result);
$("#parameter_select label").text(result);
}
});
Any ideas what am I doing wrong here?
This happens because AJAX-calls by default use browser's default encoding (f.e. ANSI). For overriding this you need to do:
jQuery style - mimeType:
$.ajax({
url: "get_label",
mimeType:"text/html; charset=UTF-8",
success: function(result)
{
alert(result);
$("#parameter_select label").text(result);
}
});
Vanilla JS style:
xhr.overrideMimeType("text/html; charset=UTF-8")
But from the other hand you need to be sure, that server also returns appropriate response. For this you need to check the following:
For this you can use either explicit call of method:
@RequestMapping("get_label")
public @ResponseBody String getLabel(HttpServletResponse response)
{
String str = "בדיקה";
//set encoding explicitly
response.setCharacterEncoding("UTF-8");
return str;
}
Or, which seems to be more preferable for @ResponseBody
and Spring 3.1+:
@RequestMapping(value = "get_label", produces = "text/html; charset=UTF-8")
public @ResponseBody String getLabel(HttpServletResponse response)
{
String str = "בדיקה";
return str;
}
As a conclusion I would like to clarify, that for proper handling of AJAX-calls with UTF-8 encoding, you have to make sure, that:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With