微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

封装自己的Ajax函数

处理data参数

需要把data对象,转化成查询字符串的格式,从而提交给服务器,因此提前定义resolveData函数如下:

定义itheima函数

在itheima()函数中,需要创建xhr对象,并监听onreadystatechange事件:

判断请求的类型

不同的请求类型,对应xhr对象的不同操作,因此需要对请求类型进行if .. else ...的判断:

 

 代码示例:

js文件

function resolveData(data){
    var arr = []
    for(var k in data){
        var str = k + '=' + data[k]
        arr.push(str)
    }
    return arr.join('&')
}
// var res = resolveData({name:'zs',age:20})
// console.log(res);
function itheima(options){
    var xhr = new XMLHttpRequest()

    // 把外界传递过来的参数对象,转换为查询字符串
    var qs = resolveData(options.data)

    if(options.method.toupperCase() === 'GET'){
        // 发起GET请求
        xhr.open(options.method,options.url + '?' + qs)
        xhr.send()
    }else if(options.method.toupperCase() === 'POST'){
        // 发起POST请求
        xhr.open(options.method,options.url)
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.send(qs)
    }
    
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status === 200){
            var result = JSON.parse(xhr.responseText)
            options.success(result)
        }
    }
}

HTML:

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

<head>
    <Meta charset="UTF-8">
    <Meta http-equiv="X-UA-Compatible" content="IE=edge">
    <Meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="/js文件/itheima.js"></script>
</head>

<body>

</body>
<script>
    // itheima({
    //     method: 'GET',
    //     url: 'http://www.liulongbin.top:3006/api/getbooks',
    //     data: {
    //         id: 1
    //     },
    //     success: function (res) {
    //         console.log(res);
    //     }
    // })

    itheima({
        method: 'POST',
        url: 'http://www.liulongbin.top:3006/api/addbook',
        data: {
            bookname: 'aaa',
            author: 'bbb',
            publisher: 'ccc'
        },
        success: function (res) {
            console.log(res);
        }
    })
</script>

</html>

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐