ajax封装get、post请求

//JS如何封装一个ajax请求
//请求方式:请求地址,请求参数,请求参数的类型
//请求返回的结果
function ajax(options) {
    //创建XMLHttpRequest对象
    let xhr = new XMLHttpRequest();
    //初始化参数内容
    options = options || {}
    options.type = (options.type || 'GET').toUpperCase()
    options.dataType = options.dataType || 'json'
    const params = options.data
    //发送请求
    if (options.type === 'GET') {
        xhr.open('GET', options.url + "?" + getParams(params), true)
        xhr.send(null)
    } else if (options.type === 'POST') {
        xhr.open('POST', options.url, true)
        xhr.send(params)
    }
    //接收请求
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 & xhr.status < 300) {
                //responseText字符串的响应数据
                //responseTypeXML形式的响应数据
                options.success(xhr.responseText, xhr.responseXML)
            } else {
                options.fail('参数错误' + xhr.status)
            }
        }
    }
}

ajax({
    type: 'post',
    dataType: 'json',
    data: {
        limit: 10
    },
    url: 'http://localhost:3000/personalized',
    success: function (text, xml) {//成功的回调
        console.log(JSON.parse(text));
    },
    fail: function (status) {//失败的回调
        console.log(status);
    }
})
//对参数做处理
function getParams(data) {
    let arr = [];
    // url = 'limit=10&age=19'
    for (let key in data) {
        arr.push(`${key}=${data[key]}`)
    }
    console.log(arr.join('&'));
    return arr.join('&')
}
// 转换为数组: ['limit=10', 'age=20', 'sex=12']
// 数组使用join拼接& limit=10&age=20&sex=12
getParams({ limit: 10, age: 20, sex: 12 })

主要需要掌握ajax的原理,封装之前考虑到我们函数需要接收的参数。

getParams是为了将我们get请求中 获取到的date数据可以解析到我们的请求地址上,封装为一个函数。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值