原生ajax请求的封装

封装

function myAxios(config) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    if (config.params) {
      const paramsObj = new URLSearchParams(config.params)
      const queryString = paramsObj.toString()
      config.url += `?${queryString}`
    }
    xhr.open(config.method || 'GET', config.url)
    xhr.addEventListener('loadend', () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(JSON.parse(xhr.response))
      } else {
        reject(new Error(xhr.response))
      }
    })
    if (config.data) {
      const jsonStr = JSON.stringify(config.data)
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.send(jsonStr)
    } else {
      xhr.send()
    }
  })
}


//用法

  myAxios({
    url: 'http://hmajax.itheima.net/api/weather/city',
    method:'get',
    params: {
      city:'北京',
    }
  }).then(result => {
    const arr = result.data
  })

原生ajax请求的封装

原生ajax请求分为四步:

1.创建请求对象

判断浏览器的兼容问题
ie浏览器:window.ActiveXObject
常用浏览器:window.XMLHttpRequest

 if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

2.调用open方法

使用open()方法

3.发送请求

使用send()方法

4.判断并执行请求

判断转态 readyState是否等于 4 并且 status 是否等于 200 满足这两个条件代表请求成功

readyState有五种可能的值:

0 (未初始化): (XMLHttpRequest)对象已经创建,但还没有调用open()方法。
1 (载入):已经调用open() 方法,但尚未发送请求。
2 (载入完成): 请求已经发送完成。
3 (交互):可以接收到部分响应数据。
4 (完成):已经接收到了全部数据,并且连接已经关闭。

status 的状态

1xx Info 提示性信息:
100 Continue 告诉客户端继续发送请求,数据没有传输完成
101 Switching Protocols 协议转换
2xx Successful 成功的响应消息 :
200 OK 请求-响应成功
201 Created 创建成功

3xx Redirection 请求需要重定向到另一个URL:
301 Moved Permanently 请求的资源已被永久移走
303 See Other 另请参见另外一个网站
304 Not Modified 请求资源没有修改,请直接使用客户端缓存的资源,并不是报错,是指缓存命中了,也就是说请求的这个资源客户端缓存中存在

4xx Client Error 客户端错误:
400 Bad Request 无效的请求消息
402 Payment Required 请求资源没有付费
403 Forbidden 请求的资源不被允许访问
404 Not Found 请求的资源不存在
405 Method Not Allowed 请求方法不被服务器允许
414 Request-URI Too Long 请求的URI太大,无法解析

5xx Server Error 服务器端错误

500 Internal Server Error 服务器内部错误
503 Service Unavailable 服务器被攻击了
505 HTTP Version Not Supported 服务器版本太低

原生ajax的get、post的同步异步请求封装以及用法

// get的同步
/**
 * 
 * @param {*} url 请求文件的路径
 * @param {*} parms url后面传的参数,格式如下:name=zhang&age=18
 * @param {*} success 请求成功后,调用success函数
 * @param {*} error 请求失败后,调用error函数
 */
function getSync(url, parms, success, error) {
    if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    xhr.open('get', url + '?' + parms, false);
    xhr.send();
    if (xhr.readyState == 4 && xhr.status == 200) {
        success(xhr);
    } else {
        error('请求失败');
    }
}

// get 的异步
function getAsync(url, parms, success, error) {
    if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    xhr.open('get', url + '?' + parms, true);
    xhr.send();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                success(xhr);
            } else {
                error('请求失败');
            }
        }
    }
}

// post 同步
function postSync(url, parms, success, error) {
    if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    xhr.open('post', url, false);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(parms);
    if (xhr.readyState == 4 && xhr.status == 200) {
        success(xhr);
    } else {
        error('请求失败');
    }
}

// post异步
function postAsync(url, parms, success, error) {
    if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }

    xhr.open('post', url, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(parms);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                success(xhr);
            } else {
                error('请求失败');
            }
        }
    }
}


/*  // 封装调用测试
    getAsync('test.php', '', suc, err);

    function suc(msg) {
        console.log(msg.responseText);
    }

    function err(tip) {
        console.log(tip);
    } */


//     封装
//     get的同步getSync
//     get的异步getAsync
//     post同步postSync
//     post异步postAsync
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

夜空孤狼啸

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

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

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

打赏作者

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

抵扣说明:

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

余额充值