发生这种情况是因为 AJAX 调用默认使用浏览器的默认编码(例如 ANSI)。为了覆盖这个你需要这样做:
jQuery style http://api.jquery.com/jQuery.ajax/ - mimeType:
$.ajax({
url: "get_label",
mimeType:"text/html; charset=UTF-8",
success: function(result)
{
alert(result);
$("#parameter_select label").text(result);
}
});
香草JSstyle https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#overrideMimeType%28%29:
xhr.overrideMimeType("text/html; charset=UTF-8")
但从另一方面来说,您需要确保该服务器也返回适当的响应。为此,您需要检查以下内容:
- 添加对 Web 容器(即 Tomcat)的 UTF-8 支持URIEncoding=“UTF-8”为您连接器设置在服务器.xml; check this http://struts.apache.org/release/2.0.x/docs/how-to-support-utf-8-uriencoding-with-tomcat.html了解更多信息。
- 如果之前的更改没有帮助(尽管必须如此),还请确保 servlet 响应的字符集也是UTF-8.
为此,您可以使用显式调用方法:
@RequestMapping("get_label")
public @ResponseBody String getLabel(HttpServletResponse response)
{
String str = "בדיקה";
//set encoding explicitly
response.setCharacterEncoding("UTF-8");
return str;
}
或者,这似乎更适合@ResponseBody
和 Spring 3.1+:
@RequestMapping(value = "get_label", produces = "text/html; charset=UTF-8")
public @ResponseBody String getLabel(HttpServletResponse response)
{
String str = "בדיקה";
return str;
}
作为结论,我想澄清一下,为了正确处理使用 UTF-8 编码的 AJAX 调用,您必须确保:
- web-container 正确支持这一点
- 响应的字符编码是UTF-8
- AJAX请求字符编码也是UTF-8