思路

失去焦点以后,发送请求,然后通过回调判断请求的结果

代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .nOerror{
            display: none;
        }
        .error{
            display: block;
        }
    </style>
</head>
<body>
<form>
    <input type="text" name="ming" id="ming"/>
    <p class="nOerror" id="error">出现错误</p>
    <input type="submit" value="提交" id="submit"/>
</form>
<script>
    // 发送post请求函数
    function postUserName(json, callback) {
        let request = new XMLHttpRequest();
        request.open("post", './login');
        request.setRequestHeader("Content-Type", "application/json;charset=utf-8");
        request.onreadystatechange = () => {
            // 如果请求完成
            if(request.readyState === 4 && request.status === 200){
                let type = request.getResponseHeader("Content-Type");
                if(type.match(/^text/)){
                    callback(request.responseText);
                }
            }
        }
        request.send(json);
    }
    // 失去焦点事件
    document.getElementById("ming").addEventListener("focusout", (event) => {
        console.log(event.srcElement.value);
        // 包装成json,发送
        let json = {};
        json.value = event.srcElement.value;
        // 成为json发送
        json = JSON.stringify(json);
        // 定义回调函数
        let callback = (text) => {
            console.log(text);
            // 更改页面css样式
            let error = document.getElementById("error");
            error.className("error");
        }
        // 发送
        postUserName(json, callback);
    })
</script>
</body>
</html>