zoukankan      html  css  js  c++  java
  • 前端接收后端返回数据中【后端返回数据

    前端jQuery发送ajax请求后,后端controller接收数据并进行处理,然后将结果返回给前端的 success : function(data){} 中。

    对于不同格式的返回数据,前端 $.ajax() 中要设置对应的 dataType 值,才能保证顺利接收到这些数据。

    现将 后端返回数据的格式 - dataType 的对应关系整理如下。

    参考:https://blog.csdn.net/dreamstar613/article/details/61913970

    汇总表格

    后端返回数据类型 $.ajax({}) 中 dataType属性值
    html页面 html / 无
    Map json / 无
    Integer json / 无
    String text / 无
    实体类Class json / 无
    实体类数组ArrayList json / 无

     参考文档

    dataType

    类型:String

    预期服务器返回的数据类型。如果不指定,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": 返回纯文本字符串

    一、后端返回 html页面

    前端:

    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-normal">百搭按钮</button>
    </div>
    
    
    <div id="content-wrapper"></div>
    
    
    <script>
        $(document).ready(function () {
            $(".layui-btn-normal").click(function () {
                /**(1)用$("#content-wrapper").html(data);显示页面*/
                $.ajax({
                    cache : false,
                    type : 'POST',
                    url : '/page/test',
                    error : function() {
                        alert('smx失败 ');
                    },
                    success : function(data) {
                        $("#content-wrapper").html(data);
                    }
                });
            });
        });
    </script>

    后端:

    @Controller
    public class testController {
    
        /*
         * (1)不能有注解@ResponseBody
         */
        @RequestMapping(value = "/page/test", method = RequestMethod.POST)
        public String editAreaWithFile() {
    
            return "test";
    
        }
    
    }

    页面test.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="../static/js/jquery.min.js"></script>
    </head>
    <body>
        <div>this is the test.html.</div>
    
        <button type="button" class="btn">按钮</button>
    
        <script>
            $(document).ready(function () {
                $(".btn").click(function () {
                    alert("点击按钮");
                });
            });
        </script>
    </body>
    </html>

    效果:

    二、后端返回 Map

    前端:

    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-normal">百搭按钮</button>
    </div>
    
    
    
    <!-- Map -->
    <script>
        $(document).ready(function () {
            $(".layui-btn-normal").click(function () {
    
                $.ajax({
                    cache : false,
                    type : 'POST',
                    url : '/testReturnData2',
                    // 预期后端返回的数据类型
                    dataType : "json",
                    error : function() {
                        alert('smx失败 ');
                    },
                    success : function(data) {
                        for(var x in data){
                            console.log("x == " + x);
                            console.log("data[x] == " + data[x]);
                        }
                    }
                });
            });
        });
    </script>

    后端:

    @Controller
    public class testController {
    
        /**
         * 返回Map
         * @return Map
         * @前端dataType : "json",
         */
        @ResponseBody
        @RequestMapping(value = "/testReturnData2", method = RequestMethod.POST)
        public Map<String, String> testMap() {
            //处理参数
            HashMap<String, String> map = new HashMap<>();
            map.put("name","Tom");
            map.put("job","cat");
            map.put("age","14");
    
            return map;
        }
    }

    效果:

    三、后端返回 Integer

    前端:

    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-normal">百搭按钮</button>
    </div>
    
    
    <!-- Integer -->
    <script>
        $(document).ready(function () {
            $(".layui-btn-normal").click(function () {
    
                $.ajax({
                    cache : false,
                    type : 'POST',
                    url : '/testReturnData3',
                    // 预期后端返回的数据类型
                    dataType : "json",
                    error : function() {
                        alert('smx失败 ');
                    },
                    success : function(data) {
                        alert(data);
                    }
                });
            });
        });
    </script>

    后端:

    @Controller
    public class testController {
    
        /**
         * 返回 Integer
         * @return Integer
         * @前端dataType : "json",
         */
        @ResponseBody
        @RequestMapping(value = "/testReturnData3", method = RequestMethod.POST)
        public Integer testInteger() {
            //处理参数
            return 99;
        }
        
    }

    效果:

    四、后端返回 String

    前端:

    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-normal">百搭按钮</button>
    </div>
    
    
    <!-- String -->
    <script>
        $(document).ready(function () {
            $(".layui-btn-normal").click(function () {
    
                $.ajax({
                    cache : false,
                    type : 'POST',
                    url : '/testReturnData4',
                    // 预期后端返回的数据类型
                    dataType : "text",
                    error : function() {
                        alert('smx失败 ');
                    },
                    success : function(data) {
                        alert(data);
                    }
                });
            });
        });
    </script>

    后端:

    @Controller
    public class testController {
    
        /**
         * 返回 String
         * @return String
         * @前端dataType : "text",
         */
        @ResponseBody
        @RequestMapping(value = "/testReturnData4", method = RequestMethod.POST)
        public String testString() {
            //处理参数
            return "hello";
        }
    
    }

    效果:

    五、后端返回 实体类Class

    前端:

    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-normal">百搭按钮</button>
    </div>
    
    
    <!-- 实体类  -->
    <script>
        $(document).ready(function () {
            $(".layui-btn-normal").click(function () {
    
                $.ajax({
                    cache : false,
                    type : 'POST',
                    url : '/testReturnData5',
                    // 预期后端返回的数据类型
                    dataType: "json",
                    error : function() {
                        alert('smx失败 ');
                    },
                    success : function(data) {
                        // 返回的是object
                        alert(jQuery.type(data));
                        console.log("flag: " + data.flag);
                        console.log("name: " + data.name);
                        console.log("age: " + data.age);
                    }
                });
            });
        });
    </script>

    后端:

    @Controller
    public class testController {
    
        /**
         * 返回 实体类
         * @return 实体类对象
         * @前端dataType : 无/json
         */
        @ResponseBody
        @RequestMapping(value = "/testReturnData5", method = RequestMethod.POST)
        public Student testJavaBean() {
            //处理参数
            Student student = new Student();
            student.setFlag(1);
            student.setName("Tom");
            student.setAge(12);
    
            return student;
        }
    
    }

    实体类 Student.class:

    package com.cei.ceipage.entity;
    
    
    import lombok.Data;
    
    @Data
    public class Student {
    
        private int flag;
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(int flag, String name, int age) {
            this.flag = flag;
            this.name = name;
            this.age = age;
        }
    }

    效果:

    六、后端返回 实体类数组ArrayList

    前端:

    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-normal">百搭按钮</button>
    </div>
    
    
    <!-- 实体类集合 -->
    <script>
        $(document).ready(function () {
            $(".layui-btn-normal").click(function () {
    
                $.ajax({
                    cache : false,
                    type : 'POST',
                    url : '/testReturnData6',
                    // 预期后端返回的数据类型(无/json 都可)
                    dataType: "json",
                    error : function() {
                        alert('smx失败 ');
                    },
                    success : function(data) {
                        // 返回的是object
                        console.log("返回的data的类型:" + jQuery.type(data) + "
    
    ");
    
                        for(var x in data){
                            // String
                            console.log("x的类型:" + jQuery.type(x));
                            // Object
                            console.log("data[x]的类型:" + jQuery.type(data[x]));
    
                            // 正确输出
                            console.log("x == " + x); //按循环依次打印 0,1,2
                            console.log("data[x] == " + data[x]);
                            console.log("data[x].flag: " + data[x].flag);
                            console.log("data[x].name: " + data[x].name);
                            console.log("data[x].age: " + data[x].age + "
    
    ");
    
                            // 属性为 undefined
                            // console.log(x);
                            // console.log(x.flag);
                            // console.log(x.name);
                            // console.log(x.age);
    
                            // 属性为 undefined
                            // var xJson = JSON.parse(x);
                            // console.log(xJson.flag);
                            // console.log(xJson.name);
                            // console.log(xJson.age);
    
                            // 报错
                            // var xJson = JSON.parse(data[x]);
                            // console.log(xJson.flag);
                            // console.log(xJson.name);
                            // console.log(xJson.age);
    
                        }
    
                    }
                });
            });
        });
    </script>

    后端:

    @Controller
    public class testController {
    
        /**
         * 返回 实体类数组ArrayList
         * @return ArrayList对象
         * @前端dataType : 无/json
         */
        @ResponseBody
        @RequestMapping(value = "/testReturnData6", method = RequestMethod.POST)
        public ArrayList<Student> testJavaBeanList() {
            //处理参数
            ArrayList<Student> students = new ArrayList<>();
            Student student1 = new Student(1, "Tom", 12);
            Student student2 = new Student(0, "Jerry", 10);
            Student student3 = new Student(1, "Jim", 14);
            students.add(student1);
            students.add(student2);
            students.add(student3);
    
            return students;
        }
    
    }

    效果:

  • 相关阅读:
    点击新闻弹出新闻内容,并且新闻内容根据鼠标移动
    阻止用户复制页面上的文字的几种方法
    js简易聊天框- 鼠标和回车键发送消息
    Java——package和import关键字
    Java——static关键字
    Java——单例模式初步
    Java——this关键字
    Java面向对象的特征一:封装性
    Java再谈方法
    Java——对象
  • 原文地址:https://www.cnblogs.com/CPU-Easy/p/15124644.html
Copyright © 2011-2022 走看看