13. Ajax验证用户名

13. Ajax验证用户名

13.1 Controller

package com.liu.controller;
import com.liu.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;

@RestController
public class HelloController {
    @RequestMapping("/login")
    public String login(String name,String password){
        String msg = "";
        if (name != null) {
            if ("admin".equals(name)) {
                msg = "ok";
            } else {
                msg = "用户名有误";
            }
        }
        if (password != null) {
            if ("180018".equals(name)) {
                msg = "ok";
            } else {
                msg = "密码有误";
            }
        }
        return msg;
    }
}

13.2 jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script>
        function a(){
            $.post({
                url : "${pageContext.request.contextPath}/login",
                data :  {"name":$('#name').val()},
                success : function (data) {
                    if (data.toString()==='ok') {//jQuery直接加入节点 , 设置css与html
                        $('#userInfo').css({"color":"green"});  
                    } else {
                        $('#userInfo').css("color","red");
                    }
                    $('#userInfo').html(data);
                }
            })
        }
        function b(){
            $.post({
                url : "${pageContext.request.contextPath}/login",
                data :  {"password":$('#password').val()},
                success : function (data) {
                    if (data.toString()==='ok') {
                        $('#userInfo').css({"color":"green"});
                    } else {
                        $('#userInfo').css("color","red");
                    }
                    $('#userInfo').html(data);
                }
            })
        }
    </script>
</head>
<body>
<p>
    用户名 : <input type="text" id="name" onblur="a()">
    <span id="userInfo"></span>
</p>
<p>
    密码  : <input type="text" id="password" onblur="b()">
    <span id="passwordInfo"></span>
</p>
</body>
</html>
上一篇:【Spring框架学习】综合案例 巩固


下一篇:设计模式之美--单一职责原则