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

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

后端代码:

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

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

可以看到上面的代码返回的是Map>,注意使用了@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+= ""
            }
             aa = resp["cityInfo2"];
            var secondCity ="";
            for(var city in aa){
                secondCity+= ""
            }
             
            $("#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+= ""
            }
             aa = resp["cityInfo2"];
            var secondCity ="";
            for(var city in aa){
                secondCity+= ""
            }
 
            $("#firstCity").html(firstCity);
            $('#firstCity').selectpicker("refresh");
            $("#secondCity").html(secondCity);
            $('#secondCity').selectpicker("refresh");

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

预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断,比如 XML MIME 类型就被识别为 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 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。
•"text": 返回纯文本字符串
 

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

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

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

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

 

你可能感兴趣的:(前端)