手搓ajax的封装

ajax的封装

前言

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

同步的ajax请求

  • 同步封装ajax请求可以通过返回值的方式返回后端的数据
  • 请求参数
    • type 请求方式
    • url 请求路径
    • data 发送的数据
  • 返回值
    • 需要将后端的数据返回
js 复制代码
    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 请求成功之后执行的回调函数
  • 返回值
    • 无返回值
js 复制代码
    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)
    })

请求的参数支持对象

  • 参数为字符串会容易导致出错,传一个对象不会容易出错
js 复制代码
    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个变成一个对象
js 复制代码
    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)
        }
    })
相关推荐
一 乐5 分钟前
民宿|基于java的民宿推荐系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·源码
testleaf34 分钟前
前端面经整理【1】
前端·面试
BillKu35 分钟前
Vue3 + TypeScript + Element Plus 表格行按钮不触发 row-click 事件、不触发勾选行,只执行按钮的 click 事件
vue.js·elementui·typescript
好了来看下一题35 分钟前
使用 React+Vite+Electron 搭建桌面应用
前端·react.js·electron
啃火龙果的兔子36 分钟前
前端八股文-react篇
前端·react.js·前端框架
小前端大牛马42 分钟前
react中hook和高阶组件的选型
前端·javascript·vue.js
刺客-Andy43 分钟前
React第六十二节 Router中 createStaticRouter 的使用详解
前端·javascript·react.js
秋田君2 小时前
深入理解JavaScript设计模式之策略模式
javascript·设计模式·策略模式
萌萌哒草头将军3 小时前
🚀🚀🚀VSCode 发布 1.101 版本,Copilot 更全能!
前端·vue.js·react.js
GIS之路3 小时前
OpenLayers 图层叠加控制
前端·信息可视化