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

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>

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想在 Vue 中使用自己封装的原生 ajax,可以按照以下步骤操作: 1. 在 Vue 组件中定义一个方法,用于发送 ajax 请求: ```javascript methods: { ajax: function(options) { var xhr = new XMLHttpRequest(); //创建 XMLHttpRequest 对象 xhr.onreadystatechange = function() { if (this.readyState == 4) { //请求完成 if (this.status == 200) { //请求成功 options.success(xhr.responseText); } else { //请求失败 options.error(xhr.status); } } }; xhr.open(options.method, options.url, true); //设置请求方法和地址 xhr.send(options.data); //发送请求 } } ``` 在上述代码中,`ajax` 方法接收一个对象作为参数,包含以下属性: - `method`:请求方法,例如 `"GET"` 或 `"POST"`。 - `url`:请求地址。 - `data`:发送的数据,可以是字符串或 FormData 对象。 - `success`:请求成功时的回调函数。 - `error`:请求失败时的回调函数。 2. 在组件中调用 `ajax` 方法发送 ajax 请求: ```javascript this.ajax({ method: 'POST', url: '/api/login', data: new FormData(document.querySelector('#login-form')), success: function(response) { console.log(response); }, error: function(status) { console.log('请求失败,状态码为:' + status); } }); ``` 在上述代码中,我们通过调用 `ajax` 方法来发送一个 POST 请求,将表单数据作为参数传递给 `data` 属性。当请求成功时,会调用 `success` 回调函数,将服务器返回的数据作为参数传递给它。当请求失败时,会调用 `error` 回调函数,将 HTTP 状态码作为参数传递给它。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值