封装自己的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>
复制代码

 

posted @   今天穿秋裤了吗  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示