ajax简单封装

工做之余简单封装了ajax的请求,可是工做中仍是用jquery,axios,angular内部封装好了http模块(笑)。javascript

ajax通常分为简单的四部:java

  1. 建立ajax对象(这里兼容ie的话要作一下处理)
  2. 链接,即请求对象的open方法(get和post还有点不一样,get参数要放在url后面,post要设置请求头)
  3. 发送,即请求对象的send函数(post参数则放在send里面)
  4. 接收,在onreadystatechange(存储函数或函数名,每当readyState属性改变时,就会调用该函数。)函数里面处理。

还能够加上超时这些jquery

onreadystatechange分析

  1. 要先判断readyState的状态(有四个状态)

    ①: 0,请求未初始化;ios

    ②: 1,服务器链接已创建;ajax

    ③: 2,请求已接收;json

    ④: 3,请求处理中;axios

    ⑤: 4,请求已完成,且响应已就绪浏览器

  2. 当readyState等于4时,你又要判断status的状态
  3. 请求成功时status状态 200-300(不包括300) ,还有304(是缓存)(具体状态能够去参考文档)
  4. 在成功(失败)的回掉函数里面将xhr.responseText的值返回出去。

代码

'use strict';

var $ = {};
$.ajax = ajax;

function ajax(options) {

  // 解析参数
  options = options || {};
  if (!options.url) return;
  options.type = options.type || 'get';
  options.timeout = options.timeout || 0;

  // 1 建立ajax
  if (window.XMLHttpRequest) {

    // 高级浏览器和ie7以上
    var xhr = new XMLHttpRequest();
  } else {

    //ie6,7,8
    var xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
  }

  // 2 链接
  var str = jsonToUrl(options.data);
  if (options.type === 'get') {
    xhr.open('get', `${options.url}?${str}`, true);

    // 3 发送
    xhr.send();
  } else {
    xhr.open('post', options.url, true);

    // 请求头
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

    // 3 发送
    xhr.send();
  }

  // 接收
  xhr.onreadystatechange = function() {

    // 完成
    if (xhr.readyState === 4) {

      // 清除定时器
      clearTimeout(timer);

      if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {

        // 成功
        options.success && options.success(xhr.responseText);
      } else {
        options.error && options.error( xhr.status );
      }
    }
  };

  
  // 超时
  if (options.timeout) {
    var timer = setTimeout(function(){ 
            alert("超时了");
            xhr.abort(); // 终止
        },options.timeout);
  }
}


// json转url
function jsonToUrl(json) {
  var arr = [];
  json.t = Math.random();
  for(var name in json) {
    arr.push(name + '=' + encodeURIComponent(json[name]));
  }
  return arr.join('&');
}
相关文章
相关标签/搜索