ajax傳回值 json 亂碼 解決方案

來源:互聯網
上載者:User

標籤:ajax傳回值 json 亂碼 解決方案

ajax的傳回值一直亂碼,

試過各種ContentType設定utf-8的方法,就是搞不定,

而且明明傳回值是json字串,一直出現ajax取得傳回值類型為object。


最後查資料發現,

SpringMVC使用 @ResponseBody註解,返加字串不做任何處理時,有可能會出現亂碼問題。

這是由於 StringHttpMessageConverter 類中,預設採用的字元集是 ISO-8859-1。

public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {           public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");


解決辦法:


    那麼要解決亂碼問題,需要改變 StringHttpMessageConverter 中的預設字元集,本文中以UTF-8為例。

   

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">        <property name="messageConverters">            <list>                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">                    <property name="supportedMediaTypes">                        <list>                            <value>text/html;charset=UTF-8</value>                            <value>text/plain;charset=UTF-8</value>                            <value>application/json;charset=UTF-8</value>                        </list>                    </property>                </bean>            </list>        </property>    </bean>        <!-- mvc:annotation-driven/-->    <mvc:annotation-driven validator="validator"/>
註:配置必須在 <mvc:annotation-driven /> 之前,否則將不會啟效;<mvc:annotation-driven /> 會自動註冊DefaultAnnotationHandlerMapping 與AnnotationMethodHandlerAdapter。


ajax傳回值 json 亂碼 解決方案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.