ajax的封装——jq简化版

最近在复习ajax的知识,练习了下ajax的封装,此处做下笔记
废话不多说,直接代码

//发请求
//此处的url为请求地址,type为请求方式,success为请求成功的回调函数
myaxios({
            url: 'http://127.0.0.1:8080/doRegister', 
            type: 'post',
            data: {
                userName: '狗子',
                password: '12323',
                phone: '12154545', 
            },
            success:function(res) {
                    console.log(res)
                }
        })

function myaxios(config={}) { 	//将值以一个兑现的方式传入
        const {
            url,
            type,
            data,
            success
        } = config
        let xhr = new XMLHttpRequest();
  		  //由于get方法与post方法数据请求的方式不同,需要做下处理
        let arr = []
        if (type.toLowerCase === 'get') {
            for (let key in data) {
                arr.push(`${key}=${data[key]}`)
            }
            //需要装化为 键=值&键=值的方式
            url = url + '?' + arr.join('&')
        }

        xhr.open(type, url);
    	//请求方式若为post
        if (type.toLowerCase === 'post') {
            for (let key in data) {
                arr.push(`${key}=${data[key]}`)
            }
            //设置请球头,使其以键值对的方式传输数据
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            // 然后发送请求
            xhr.send(data);
        } else {
            xhr.send();
        }
        xhr.onreadystatechange = function () {
            if (xhr.status === 200 && xhr.readyState === 4) {
                //console.log(xhr.responseText)
                if (xhr.getResponseHeader('Content-Type').indexOf('json') !== -1) {
                    // 证明 content-type 这个响应头里面包含 json ,证明返回的就是json格式字符串
                    response = JSON.parse(xhr.responseText);
                    success(response)
                    
                }
               
            }
        }
    }
原文地址:https://www.cnblogs.com/axu1997/p/12495194.html