Bad coding when returning a string using Spring MVC & ajax

I have a webpage that requests a text string using Ajax, but the string is returned as '??????'

It is strange that when you insert the same line into a page using JSTL, not Ajax, it displays correctly ...

On my webpage I declare

<%@ page contentType="text/html" pageEncoding="UTF-8"%>

What is 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 I'm doing wrong here?

+5
source share
1 answer

This is because, by default, AJAX calls use the default encoding of the browser (for example, ANSI). To do this, you need to do the following:

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")

, . :

  • UTF-8 - ( Tomcat) URIEncoding = "UTF-8" server.xml; .
  • ( ), , , 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;
}

, AJAX- UTF-8 , :

  • -
  • - UTF-8
  • AJAX UTF-8
+14

All Articles