手写一个ajax

224 阅读1分钟

AJAX

AJAX可以实现在页面不刷新的情况下向服务器发送请求,从而实现页面与服务器的异步交互。

缺点

  1. 没有历史记录,不能前进和回退
  2. 不能发送跨域请求
  3. SEO不友好,爬虫爬不到

AJAX请求发送步骤

  1. 创建一个XMLHttpRequest对象xhr
  2. xhr.open(‘请求类型’,URL)发送请求
  3. xhr.setRequestHeader('请求头名字','请求头的值')设置请求头信息
  4. xhr.onreadystatechange = function(){}事件绑定处理请求结果
  5. xhr.send()发送请求,可以携带参数
function getJSON(url) {
  return new Promise((resolve, reject) => {
    //定义一个xhr对象
    let xhr = new XMLHttpRequest();
    
    //设置请求超时处理
    xhr.timeout = 2000
    //请求超时的回调
    xhr.ontimeout = function(){
      console.log('请求超时')
    }
    
    //xhr.open()设置请求类型和url
    xhr.open('GET', url);
    //设置请求头信息
    xhr.setRequestHeader('Accept', 'application/json');
    //绑定函数接收请求数据
    xhr.onreadystatechange = function () {
      //判断返回的状态码
      if (xhr.readyState != 4) return;
      if (xhr.status == 200 || xhr.status == 304) {
        resolve(xhr.responseText)
      }else{
        reject(new Error(xhr.responseText))
      }
    }
    xhr.send();
  })


}