【SpringMVC】10 对Ajax的应用

编写一个AjaxController

package cn.dai.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ArkD42
 * @file SpringMVC
 * @create 2020 - 05 - 07 - 17:38
 */
@RestController
public class AjaxController {

    @GetMapping("/ajax01")
    public String getAjax(){
        return "hello";
    }

    @PostMapping("/a11")
    public void getAjax2(String name, HttpServletResponse response) throws IOException {
        System.out.println("a1 is ? " + name);
        if ("DZZ".equals(name)) response.getWriter().println("YES YOU ARE");
        else response.getWriter().println("NO FUCK OFF");
    }
}

 

编写发送页的JSP

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <script
            src="http://code.jquery.com/jquery-3.5.1.js"
            integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
            crossorigin="anonymous"
    >
    </script>

    <script>
        function a() {
            $.post({
                url:"${pageContext.request.contextPath}/a11",
                data:{"name":$("#username").val()},
                success:function (data) {
                    alert(data);
                },
                error:function () {

                }
            })
        }

    </script>

</head>
<body>
    <p>用户名 <input type="text" id="username" onblur="a()"></p>
</body>
</html>

 

开始测试

当输入框失去焦点时,就会弹出警告窗口

 

要注意的一点是,如果控制器的方法不是Get处理,就会发生很奇怪的事情

 


 

posted @ 2020-05-07 20:02  emdzz  阅读(142)  评论(0编辑  收藏  举报