自己封装的ajax,以及使用介绍

本文介绍了前端表单的注册和登录实现,结合防抖和节流函数,使用自定义的Ajax封装函数进行数据提交。Ajax封装函数支持POST和GET方法,对参数和回调函数进行了严格校验。同时展示了如何在注册表单中应用防抖技术,以优化用户名验证的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ajax封装(只适用于POST以及GET)传入的参数都是必传入的,解构方法解构的数据没有默认值设置 

// 防抖
function antishake(func, wait) {
    let timer = null
    return function () {
        clearTimeout(timer)
        timer = setTimeout(() => {
            func()
        }, wait)
    }
}
// 节流
function throttle(func,wait){
    // let timer = null//节流阀
    let flag = false
    return function(){
        
        if(flag) return// null====>false 如果是null(false)就执行下面代码(下面代码执行timer就变为true了),不是null就返回直接跳过     车上没人就上车 车上有人就直接跳过
        flag = true
        let timer = setTimeout(()=>{//上车了 车上有人
            func() // 到站了
            // timer = null // 下车
            flag = false
        },wait)

    }
}
// ajax封装 只适用于post+get
function ajax(object) {
    let {method,url,aync,data,dataType,callback} = object
    let keys = Object.keys(data)
    let values = Object.values(data)
    //url地址没有传递或者传递是空值 直接出去
    if(!url || url==''){
        throw new Error('url地址必须不为空') //抛出一个错误
    }
    if(typeof callback != "function"){
        throw new Error('回调函数错误')
    }
    if(typeof aync != "boolean"){
        throw new Error('aync必须是boolean类型')
    }
    //1.创建请求对象
    let xhr = createXhr()
    // 2、设置请求
    // xhr.open(method, url ,aync)
    // 字符串接收data数据 方式get加到url上面 方式post加到send上面
    let str = ''
    for (let i = 0; i < keys.length; i++) {
        str += `${keys[i]}=${values[i]}&`
    }
    // 取消最后一个&
    str = str.slice(0, -1)
    // 方式get加到url上面 方式post加到send上面
    if (method == "GET" || method == "get") {
        url = url + "?"
        url += str
        xhr.open(method, url, aync)
        // 3、发送请求
        // xhr.send()
    } else if (method == "POST" || method == "post") {
        console.log(str)
        xhr.open(method, url, aync)
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        // 3、发送请求
        // xhr.send(str)
    }else{
        throw new Error('请求方式错误')
    }
    xhr.send(str)
    // 4、监听
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && /^20\d$/.test(xhr.status)) {
            //5.接收响应
            if(dataType == "json"){
                let res = JSON.parse(xhr.responseText)
                callback(res)
            }else{
                callback(xhr.responseText)
            }
            
            
        }
    }
}
//兼容各大浏览器
function createXhr() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest()
    }
    return new ActiveXObject("Microsoft.XMLHTTP"); //兼容ie6
}

注册 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        form div {
            border: 16px solid black;
            width: 454px;
            height: 504px;
            margin: 0 auto;
        }

        form div table {
            margin-left: 28px;
            width: 366px;
            height: 100%;
        }

        form div table tbody tr:nth-of-type(1) td {
            height: 70px;
        }

        /* form div table tbody tr:nth-of-type(2) td, form div table tbody tr:nth-of-type(3) td, form div table tbody tr:nth-of-type(4) td{
            height: 60px;
            border-bottom: solid 2px black;
        } */

        form div table tbody :is(tr:nth-of-type(2), tr:nth-of-type(3), tr:nth-of-type(4)) td {
            height: 60px;
            border-bottom: solid 2px red;
        }

        form div table tbody tr:nth-of-type(5) td {
            height: 60px;
        }

        /* form div table tbody tr:nth-of-type(2) td img, form div table tbody tr:nth-of-type(3) td img, form div table tbody tr:nth-of-type(4) td img{
            margin-bottom: -8px;
        } */

        form div table tbody :is(tr:nth-of-type(2), tr:nth-of-type(3), tr:nth-of-type(4)) td img {
            margin-bottom: -8px;
        }

        form div table tbody tr:nth-of-type(5) td img {
            margin-bottom: -2px;
        }

        #login {
            width: 100%;
            height: 40px;
            background-color: blue;
        }

        input {
            margin-left: 10px;
            border-style: none;
            height: 60%;
            margin-left: -4px;
        }

        form div table tbody tr:nth-of-type(6) td input {
            margin-left: 0;
        }

        a {
            text-decoration: none;
        }
    </style>
</head>

<body>
    <form action="#" method="GET">
        <div>
            <table>
                <tbody align="center">
                    <tr>
                        <td><img src="./image/logo.jpg" alt=""></td>
                    </tr>
                    <tr align="left">
                        <td>
                            <label for="userName"><img src="./image/icon1.jpg" alt=""></label>
                            <input type="text" id="userName" placeholder="请输入用户名">
                        </td>
                    </tr>
                    <tr align="left">
                        <td>
                            <label for="userPassword"><img src="./image/icon2.jpg" alt=""></label>
                            <input type="text" id="userPassword" placeholder="请输入密码">
                        </td>
                    </tr>
                    <tr align="left">
                        <td>
                            <label for="userAge"><img src="./image/icon3.jpg" alt=""></label>
                            <input type="text" id="userAge" placeholder="请输入年龄">
                        </td>
                    </tr>
                    <tr align="left">
                        <td>
                            <label for="userPhone"><img src="./image/icon3.jpg" alt=""></label>
                            <input type="text" id="userPhone" placeholder="请输入电话">
                        </td>
                    </tr>
                    <tr align="left">
                        <td>
                            <label for="realName"><img src="./image/icon3.jpg" alt=""></label>
                            <input type="text" id="realName" placeholder="请输入真名">
                        </td>
                    </tr>
                    <tr align="left">
                        <td>
                            <img src="./image/icon4.jpg" alt="">
                            <a href="#">忘记密码</a>
                        </td>
                    </tr>
                    <tr valign="top">
                        <td><input type="submit" value="注册" id="login"></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </form>
    <script src="./myajax.js"></script>
    <script>
        // 获取元素
        let userName = document.getElementById('userName')
        let userPassword = document.getElementById('userPassword')
        let userAge = document.getElementById('userAge')
        let userPhone = document.getElementById('userPhone')
        let realName = document.getElementById('realName')
        let login = document.getElementById('login')

        // 点击提交
        login.onclick = function (e) {
            e = e || window.event
            // 阻止默认事件(表单)
            e.preventDefault()
            ajax({
                method: "POST",
                url: "http://useker.cn/reg",
                aync: true,
                data: {
                    uname: userName.value,
                    upwd: userPassword.value,
                    uage: userAge.value,
                    uphone: userPhone.value,
                    realname: realName.value
                },
                dataType: "json",
                callback: function (res) {
                    console.log(res)
                }
            })
        }

        // userName输入停止后(防抖)3秒后验证
        let antishake1 = antishake(function () {
            ajax({
                method: "get",
                url: "http://useker.cn/checkName",
                aync: true,
                data: {
                    uname: userName.value,
                    upwd: userPassword.value,
                    uage: userAge.value,
                    uphone: userPhone.value,
                    realname: realName.value
                },
                dataType: "json",
                callback: function (res) {
                    console.log(res)
                }
            })
        }, 3000)
        userName.oninput = function () {
            antishake1()
        }
    </script>
</body>

</html>

 

 

 

登录

 ​​​

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="#" method="GET">
        <table>
            <tbody>
                <th>登录</th>
                <tr align="left">
                    <td>
                        <label for="userName"><img src="./image/icon1.jpg" alt=""></label>
                        <input type="text" id="userName" placeholder="请输入用户名">
                    </td>
                </tr>
                <tr align="left">
                    <td>
                        <label for="userPassword"><img src="./image/icon2.jpg" alt=""></label>
                        <input type="text" id="userPassword" placeholder="请输入密码">
                    </td>
                </tr>
                <tr valign="top">
                    <td><input type="submit" value="登录" id="login"></td>
                </tr>
            </tbody>
        </table>
        <button class="btnAll">查询所有</button>
        <button class="btnUser">查询用户名</button>
        <button class="btnDel">删除用户</button>
    </form>
    <script src="./myajax.js"></script>
    <script>
        // 获取元素
        let userName = document.getElementById('userName')
        let userPassword = document.getElementById('userPassword')
        let login = document.getElementById('login')
        // 登录
        login.onclick = function (e) {  
            e = e || window.event
            // 阻止默认事件(表单)
            e.preventDefault()
            ajax({
                method: "POST",
                url: "http://useker.cn/login",
                aync: true,
                data: {
                    uname: userName.value,
                    upwd: userPassword.value
                },
                dataType: "json",
                callback: function (res) {
                    console.log(res)
                }
            })
        }
        // 查询所有
        let btnAll = document.querySelector(".btnAll")
        btnAll.onclick = function(e){
            e = e || window.event
            // 阻止默认事件(表单)
            e.preventDefault()
            ajax({
                method: "GET",
                url: "http://useker.cn/getUsers",
                aync: true,
                data: {},
                dataType: "json",
                callback: function (res) {
                    console.log(res)
                }
            })
        }
        // 查询用户名
        let btnUser = document.querySelector(".btnUser")
        btnUser.onclick = function(e){
            e = e || window.event
            // 阻止默认事件(表单)
            e.preventDefault()
            ajax({
                method: "GET",
                url: "http://useker.cn/getByName",
                aync: true,
                data: {uname:userName.value},
                dataType: "json",
                callback: function (res) {
                    console.log(res)
                }
            })
        }
        // 删除
        let btnDel = document.querySelector(".btnDel")
        btnDel.onclick = function(e){
            e = e || window.event
            // 阻止默认事件(表单)
            e.preventDefault()
            ajax({
                method: "POST",
                url: "http://useker.cn/delete",
                aync: true,
                data: {uname:userName.value},
                dataType: "json",
                callback: function (res) {
                    console.log(res)
                }
            })
        }
    </script>
</body>
</html>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值