前端接收后端返回數據中【后端返回數據 - dataType屬性值】總結及示例


 

前端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) + "\n\n");

                    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 + "\n\n");

                        // 屬性為 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;
    }

}

效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM