ajax请求返回map,前端获取结果

因业务需求,今天需要ajax请求的时候从后端返回一个map,但是问题是怎么在前端取值,这个以前遇到过,以为会比较简单,但是百度很多答案都不完整,导致没有办法借鉴。这里做下记录

后端代码:

@RequestMapping(value="/getCityByLevel.action", method = RequestMethod.POST)
    public @ResponseBody Object getCityByLevel() {
        //查询一线城市
        List<RhCityDto> cityInfo = rhCityService.listCityByLevel("");
        List<RhCityDto> cityInfo1 = new ArrayList<RhCityDto>();
        List<RhCityDto> cityInfo2 = new ArrayList<RhCityDto>();

        for(RhCityDto info :cityInfo){
            if(CITY_LEVEL_ONE.equals(info.getLevel())){
                cityInfo1.add(info);
            }else{
                cityInfo2.add(info);
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("cityInfo1",cityInfo1);
        map.put("cityInfo2",cityInfo2);
        return map;
    }

可以看到上面的代码返回的是Map<String,List>,注意使用了@ResponseBody注解

前端请求和处理代码:

/**
 * 城市下拉复选框内容赋值
 */
function initCity(){
    var json = {
    };
    $.ajax({
        type: "POST",
        url: "../bireport/getCityByLevel.action",
        contentType : "application/json",
        dataType:"json",
        data: JSON.stringify(json),
        success: function(resp){
            //这里的cityInfo1是后端map的key
            var aa = resp["cityInfo1"];
            var firstCity ="";
            for(var city in aa){
                firstCity+= "<option value='"+aa[city].code+"'>"+aa[city].name+"</option>"
            }
             aa = resp["cityInfo2"];
            var secondCity ="";
            for(var city in aa){
                secondCity+= "<option value='"+aa[city].code+"'>"+aa[city].name+"</option>"
            }
             
            $("#firstCity").html(firstCity);
            $('#firstCity').selectpicker("refresh");
            $("#secondCity").html(secondCity);
            $('#secondCity').selectpicker("refresh");

        },
        error:function(resp){
            $.messager.alert('出错了','系统出错,请联系管理员。','error');
        }
    });
}

上面的dataType声明为"json"

注意点:

1前端发送ajax请求时dataType一定声明为"json"

ajax请求dataType值为json,jquery就会把后端返回的字符串尝试通过JSON.parse()尝试解析为js对象。所以如果你不将dataType设置为json,可以这样自己用json解析,如下:

/**
 * 城市下拉复选框内容赋值
 */
function initCity(){
    var json = {
    };
    $.ajax({
        type: "POST",
        url: "../bireport/getCityByLevel.action",
        contentType : "application/json",
        dataType:"text",
        data: JSON.stringify(json),
        success: function(resp){
            //自己进行json解析也可以
            resp = JSON.parse(resp);
            var aa = resp["cityInfo1"];
            var firstCity ="";
            for(var city in aa){
                firstCity+= "<option value='"+aa[city].code+"'>"+aa[city].name+"</option>"
            }
             aa = resp["cityInfo2"];
            var secondCity ="";
            for(var city in aa){
                secondCity+= "<option value='"+aa[city].code+"'>"+aa[city].name+"</option>"
            }
 
            $("#firstCity").html(firstCity);
            $('#firstCity').selectpicker("refresh");
            $("#secondCity").html(secondCity);
            $('#secondCity').selectpicker("refresh");

        },
        error:function(resp){
            $.messager.alert('出错了','系统出错,请联系管理员。','error');
        }
    });
}

预期服务器返回的数据类型。如果不指定,jQuery将自动根据HTTP包MIME信息来智能判断,比如XMLMIME类型就被识别为XML。在1.4中,JSON就会生成一个JavaScript对象,而script则会执行这个脚本。随后服务器端返回的数据会根据这个值解析后,传递给回调函数。可用值:

“xml”:返回XML文档,可用jQuery处理。
“html”:返回纯文本HTML信息;包含的script标签会在插入dom时执行。
“script”:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了"cache"参数。注意:在远程请求时(不在同一个域下),所有POST请求都将转为GET请求。(因为将使用DOM的script标签来加载)
“json”:返回JSON数据。
“jsonp”:JSONP格式。使用JSONP形式调用函数时,如"myurlcallback="jQuery将自动替换为正确的函数名,以执行回调函数。
“text”:返回纯文本字符串

2后台方法的声明需要使用@responseBody??

@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。

这个注解表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用。

在使用@RequestMapping后,返回值通常解析为跳转路径。加上@responsebody后,返回结果直接写入HTTP response body中,不会被解析为跳转路径。比如异步请求,希望响应的结果是json数据,那么加上@responsebody后,就会直接返回json数据。

猜你喜欢

转载自blog.csdn.net/m0_54850604/article/details/123613802