使用ajax請求 返回Json出現亂碼解決方法

1:在使用ajax請求後臺訪問數據的數據,後臺返回的數據是亂碼,帶??問號的亂碼,之前還一直沒有遇到過,在這裏記錄整理一下,貼出解決代碼! 
(1):前臺使用ajax ,已經設定返回的結果爲json格式!ajax代碼不貼出來了! 

(2):後臺代碼

@RequestMapping(value = { "/hello/{uuid}" }, method = RequestMethod.GET /*,produces = "text/html;charset=UTF-8"*/)
    @ResponseBody
    public String hello(@PathVariable("uuid") String uuid) {
        String result = "";

        //do something  
        //使用Json返回json格式數據

        return JSON.toJSONString(result);;
    }

在沒有加produces = “text/html;charset=UTF-8” 之前,返回的結果一直是亂碼,很奇怪,項目中web.xml也設置了編碼格式utf-8 ,沒有找到最終的原因,不過找到了這種解決方法!

2:如果上面的方法還是不能解決的話就用下面的方法:

@ResponseBody
    public void hello(@PathVariable("uuid") String uuid,HttpServletResponse response) {
        String result = "";

        //do something  
        //使用Json返回json格式數據
        JSONObject josn = new JSONObject();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(JSON.toJSON(result));
    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章