Spring MVC框架:第十一章:Ajax

Ajax
Ajax程序和服務(wù)器數(shù)據(jù)傳輸


在進行Ajax操作時,SpringMVC會需要將JSON數(shù)據(jù)和Java實體類進行相互轉(zhuǎn)換,為了實現(xiàn)這個效果需要額外加入jackson-all-1.9.11.jar

1.從瀏覽器發(fā)送數(shù)據(jù)給handler方法
1請求參數(shù)分散提交

頁面:

<button id="btn1">實驗1:發(fā)送零散數(shù)據(jù)</button>

    1

jQuery:

<script type="text/javascript" src="${pageContext.request.contextPath }/jQuery/jquery-3.2.1.js"></script>
<script type="text/javascript">
    $(function(){
        $("#btn1").click(function(){
            //實驗1:發(fā)送零散數(shù)據(jù)
            //請求地址
            var url = "${pageContext.request.contextPath }/one";
            
            //請求參數(shù)
            var param = {"empId":20,"userName":"tom","random":Math.random()};
            
            //服務(wù)器端成功返回響應(yīng)后的回調(diào)函數(shù)
            var callBack = function(response){
                console.log(response);
            };
            
            //服務(wù)器端返回的響應(yīng)體數(shù)據(jù)的解析方式
            var type = "text";
            
            //發(fā)送POST方式的Ajax請求
            $.post(url, param, callBack, type);
        });
    });
</script>

handlers:

//@ResponseBody表示使用handler方法的返回值作為響應(yīng)體,不再前往任何一個視圖
    @ResponseBody
    
    //使用produces="text/html;charset=UTF-8"設(shè)置解決響應(yīng)數(shù)據(jù)亂碼問題
    //如果是JSON數(shù)據(jù)內(nèi)容類型是:application/json
    @RequestMapping(value="/one",produces="text/html;charset=UTF-8")
    public String one(
                @RequestParam("empId") Integer empId,
                @RequestParam("userName") String userName) {
        
        System.out.println("empId="+empId);
        System.out.println("userName="+userName);
        
        return "執(zhí)行成功?。?!";
    }

 

在這個例子中,handler方法接收數(shù)據(jù)和之前是沒有什么區(qū)別的,新的知識點是@ResponseBody注解。這個注解的作用是把當前handler方法的返回值直接作為響應(yīng)數(shù)據(jù)返回給瀏覽器而不是進行視圖名稱的解析。

2發(fā)送對應(yīng)POJO的數(shù)據(jù)
頁面:

<button id="btn2">實驗2:發(fā)送對應(yīng)POJO的數(shù)據(jù)</button>

 

jQuery:

$("#btn2").click(function(){
        //實驗2:發(fā)送對應(yīng)POJO的數(shù)據(jù)
        var url = "${pageContext.request.contextPath }/two";                
        var param = {
                "stuId":5,
                "stuName":"jerry",
                "stuSubject":"java",
                "random":Math.random()
            };                
        var callBack = function(response){
            console.log(response);
        };                
        var type = "text";                
        //發(fā)送POST方式的Ajax請求
        $.post(url, param, callBack, type);
});

handlers:

@ResponseBody
    @RequestMapping(value="/two",produces="text/html;charset=UTF-8")
    public String two(Student student) {
        
        System.out.println(student);
        
        return "執(zhí)行成功?。?!";
    }

   

這里又用到了@RequestBody注解,它的作用是把請求體中的JSON數(shù)據(jù)轉(zhuǎn)換成我們指定的數(shù)據(jù)類型。同時在@RequestMapping注解上我們額外增加了produces屬性用來指定響應(yīng)體數(shù)據(jù)的編碼方式,以此來解決響應(yīng)數(shù)據(jù)的字符亂碼問題。

大家可以記住這個結(jié)論:使用@ResponseBody返回響應(yīng)數(shù)據(jù)時,需要在@RequestMapping注解中使用produces="application/json;charset=UTF-8"來解決字符集問題。
3發(fā)送JSON請求體

<button id="btn3">實驗3:發(fā)送JSON請求體</button>

 

jQuery:

$("#btn3").click(function(){
    //1.創(chuàng)建數(shù)組對象
    var stuArray = new Array();
    //2.準備要存入數(shù)組的數(shù)據(jù)
    var stu01 = {"stuId":11,"stuName":"tom11","stuSubject":"php11"};
    var stu02 = {"stuId":22,"stuName":"tom22","stuSubject":"php22"};
    var stu03 = {"stuId":33,"stuName":"tom33","stuSubject":"php33"};
    //3.存入數(shù)組
    stuArray.push(stu01);
    stuArray.push(stu02);
    stuArray.push(stu03);
    //4.將數(shù)組對象轉(zhuǎn)換成字符串
    var requestBodyData = JSON.stringify(stuArray);
    //5.發(fā)送Ajax請求
    $.ajax({
        "url":"${pageContext.request.contextPath }/three",    //請求地址
        "contentType":"application/json;charset=UTF-8",        //請求體的內(nèi)容類型
        "data":requestBodyData,                                //發(fā)送給服務(wù)器的數(shù)據(jù),將來的請求體
        "dataType":"text",                                    //預(yù)期服務(wù)器返回的響應(yīng)體類型
        "success":function(response){console.log(response)},//服務(wù)器成功返回響應(yīng)后的回調(diào)函數(shù)
        "type":"POST"                                        //發(fā)送請求的請求方式
    });
});

handlers:

@ResponseBody
@RequestMapping(value="/three",produces="text/html;charset=UTF-8")
//@RequestBody將請求體的JSON數(shù)據(jù)轉(zhuǎn)換為Java類型
public String three(@RequestBody List<Student> stuList) {        
    for (Student student : stuList) {
        System.out.println(student);
    }
    
    return "執(zhí)行成功?。?!";
}

 

4.接收文本

<button id="btn4">實驗4:接收文本</button>

 

jQuery:

$("#btn4").click(function(){
    //實驗4:接收文本
    var url = "${pageContext.request.contextPath }/four";
    var callBack = function(response) {
        console.log(response);
        console.log(response.stuName);
    };
    
    //如果服務(wù)器返回的是JSON字符串,但是type="text",那么response將僅僅是一個字符串,
    //不能直接訪問JSON數(shù)據(jù)的屬性
    var type = "text";
    $.post(url, callBack, type);
});

   

handlers:

@ResponseBody
@RequestMapping(value="/four",produces="text/html;charset=UTF-8")
public String five() {
    return "來自服務(wù)器端的回應(yīng)……";
}

   

5.接收JSON

實驗5:接收JSON

JQuery:

    $("#btn5").click(function(){
        //實驗5:接收JSON
        var url = "${pageContext.request.contextPath }/five";
        var callBack = function(response) {
            console.log(response);
            console.log(response.stuName);
            //如果服務(wù)器返回的響應(yīng)體數(shù)據(jù)無法解析為JSON數(shù)據(jù),那么后續(xù)操作無法執(zhí)行,而且沒有錯誤提示。
            //console.log("aaaaaaaaaa........");
        };
        
        var type = "json";
        $.post(url, callBack, type);
    });

  

handlers:

@ResponseBody
@RequestMapping(value="/five",produces="application/json;charset=UTF-8")
public Student four() {
    return new Student(55, "stuName555", "stuSubject555");
}

接收服務(wù)器返回的數(shù)據(jù)時一定要讓jQuery的解析方式和實際返回數(shù)據(jù)的格式一致。

 

@PathVariable和@RequestParam

/emp/remove/23
@PathVariable(“empId”)

/emp/remove?empId=23
@RequestParam(“empId”)