Ajax中get方式url传递中文参数乱码的解决

时间:2019-01-18
本文章向大家介绍Ajax中get方式url传递中文参数乱码的解决,主要包括Ajax中get方式url传递中文参数乱码的解决使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. 在使用Ajax的时候使用url传递中文参数在控制器接收的数据是乱码,查了一下资料原因是:

JQuery默认的contentType:application/x-www-form-urlencoded,这才是JQuery正在乱码的原因,在未指定字符集的时候,是使用ISO-8859-1,ISO8859-1,通常叫做Latin-1,Latin-1包括了书写所有西方欧洲语言不可缺少的附加字符。JQuery的Ajax根本没有考虑到国际化的问题,使用了欧洲的字符集,所以才引起了传递中文出现乱码的问题。

大概的意思是Jquery中使用ISO8859-1编码,在控制器中使用UTF-8来进行解码所以导致了乱码的问题

2. 解决办法:

①在jsp页面中Ajax的url的中使用Jquery的encodeURI()方法可把字符串作为 URI 进行编码,encodeURL函数主要是来对URI来做转码,它默认是采用的UTF-8的编码,可以参看下面的例子:

$.ajax({
            type : "GET",
            url :  encodeURI("${APP_PATH}/getAllMajorNameIDAccordingInstituteName?instituteName=" + instituteValue),
            success : function(result){
                $.each(result.map.allMajorNames, function(){
                    var option = $("<option></option>").append(this).attr("value", this);
                    option.appendTo("#add_major");
                });
            }
});

②在后台的控制器中使用utf-8的方式来进行解码:获取参数的时候参数的名字要与之前ajax中使用的参数名字要一样,使用HttpServletRequest来获取jsp页面中传递的参数值

    @ResponseBody
    @RequestMapping("/getAllMajorNameIDAccordingInstituteName")
    public Object getAllMajorNameIDAccordingInstituteName(HttpServletRequest request) throws UnsupportedEncodingException{
        String instituteName = new String(request.getParameter("instituteName").getBytes("ISO-8859-1"), "UTF-8");   
        AjaxResult result = new AjaxResult();
        String instituteid = instituteService.queryInstituteNameByInstituteId(instituteName);
        List<String> allMajorIDs = majorService.getAllMajorID(instituteid);
        System.out.println(allMajorIDs);
        List<String> allMajorNames = new ArrayList<String>();
        for(int i = 0; i < allMajorIDs.size(); i++){
            allMajorNames.add(majorService.queryMajorNameByMajorId(allMajorIDs.get(i)));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("allMajorNames", allMajorNames);
        result.setMap(map);
        result.setRes(true);
        return result;
    }

我们可以在控制台中打印出重新编码之后的参数的名字就知道中文的乱码有没有解决了