手搓ajax的封装

ajax的封装

前言

每一次发送请求我们都需要重复创建实例,配置请求 发送请求 获取数据,为了能够使用更加方便,我们对于ajax请求的步骤进行封装

同步的ajax请求

  • 同步封装ajax请求可以通过返回值的方式返回后端的数据
  • 请求参数
    • type 请求方式
    • url 请求路径
    • data 发送的数据
  • 返回值
    • 需要将后端的数据返回
    function ajax(type, url, data){
        const xhr = new XMLHttpRequest
        if(type === 'get'){
            // get请求参数拼接在地址栏后面
            xhr.open(type, url+data, false)
            xhr.send()
        }else{
            // post请求参数放在send函数里面
            xhr.open(type, url, false)
            // 设置请求头
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            // 去除前面的?
            xhr.send(data.slice(1))
        }
        return xhr.responseText
    }
    // 调用
    let res = ajax('get', 'http://localhost:8888/test/third', '?name=jack&age=18')
    console.log(res)
    let res2 = ajax('post', 'http://localhost:8888/test/fourth', '?name=jack&age=18')
    console.log(res2)

异步的ajax请求

  • 异步封装ajax请求无法通过返回值的方式返回后端的数据,需要借助回调函数的方式返回后端的数据
  • 请求参数
    • type 请求方式
    • url 请求路径
    • data 发送的数据
    • success 请求成功之后执行的回调函数
  • 返回值
    • 无返回值
    function ajax(type, url, data, success){
        const xhr = new XMLHttpRequest
        if(type === 'get'){
            // get请求参数拼接在地址栏后面
            xhr.open(type, url+data, true)
            xhr.send()
        }else{
            // post请求参数放在send函数里面
            xhr.open(type, url, true)
            // 设置请求头
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            // 去除前面的?
            xhr.send(data.slice(1))
        }
        xhr.onload = function(){
            // 调用回调函数返回后端的数据
            success(xhr.responseText)
        }
    }
    // 调用
    ajax('get', 'http://localhost:8888/test/third', '?name=jack&age=18', function(res){
        console.log(res)
    })
        
    ajax('post', 'http://localhost:8888/test/fourth', '?name=jack&age=18', function(res){
        console.log(res)
    })

请求的参数支持对象

  • 参数为字符串会容易导致出错,传一个对象不会容易出错
    function ajax(type, url, data, success){
        const xhr = new XMLHttpRequest
        if(Object.prototype.toString.call(data) === '[object Object]'){
            let str = '?'
            for(let key in data){
                str += `${key}=${data[key]}&`
            }
            data = str.slice(0,-1)
        }
        if(type === 'get'){
            // get请求参数拼接在地址栏后面
            xhr.open(type, url+data, true)
            xhr.send()
        }else{
            // post请求参数放在send函数里面
            xhr.open(type, url, true)
            // 设置请求头
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            // 去除前面的?
            xhr.send(data.slice(1))
        }
        xhr.onload = function(){
            // 调用回调函数返回后端的数据
            success(xhr.responseText)
        }
    }
    // 调用
    ajax('get', 'http://localhost:8888/test/third', '?name=jack&age=18', function(res){
        console.log(res)
    })
    
    ajax('post', 'http://localhost:8888/test/fourth', '?name=jack&age=18', function(res){
        console.log(res)
    })
    // 调用
    ajax('get', 'http://localhost:8888/test/third', {
        name: 'jack',
        age: 18
    }, function(res){
        console.log(res)
    })
    
    ajax('post', 'http://localhost:8888/test/fourth', {
        name: 'jack',
        age: 18
    }, function(res){
        console.log(res)
    })
        

可省略参数

  • 参数由4个变成一个对象
    function ajax(params){
        const defaultParams = {
            type: 'get',
            url: '',
            data: {},
            success: function(){

            }
        }
        // 合并默认配置
        const options = {...defaultParams,...params}
        const xhr = new XMLHttpRequest
        if(Object.prototype.toString.call(options.data) === '[object Object]'){
            let str = '?'
            for(let key in options.data){
                str += `${key}=${options.data[key]}&`
            }
            options.data = str.slice(0,-1)
        }
        if(options.type === 'get'){
            // get请求参数拼接在地址栏后面
            xhr.open(options.type, options.url+options.data, true)
            xhr.send()
        }else{
            // post请求参数放在send函数里面
            xhr.open(options.type, options.url, true)
            // 设置请求头
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            // 去除前面的?
            xhr.send(options.data.slice(1))
        }
        xhr.onload = function(){
            // 调用回调函数返回后端的数据
            options.success(xhr.responseText)
        }
    }
    // 调用
    ajax({
        type: 'get',
        url: 'http://localhost:8888/test/third',
        data: {
            name: 'jack',
            age: 18
        },
        success: function(res){
            console.log(res)
        }
    })
    ajax({
        url: 'http://localhost:8888/test/third',
        data: {
            name: 'jack',
            age: 18
        },
        success: function(res){
            console.log(res)
        }
    })
    ajax({
        url: 'http://localhost:8888/test/second',
        success: function(res){
            console.log(res)
        }
    })
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苦逼的猿宝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值