博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【方法】原生js实现方法ajax封装
阅读量:4696 次
发布时间:2019-06-09

本文共 2230 字,大约阅读时间需要 7 分钟。

/* 参数说明 * type【String】 请求方式('POST'或'GET') 默认设置'GET'方式 * dataType【String】 获取到的后台数据格式 默认'JSON'格式 * async【String】 是否异步执行 默认true异步执行 * data【Object】 请求参数 * success【Function】 成功回调函数 * fail【Function】 失败回调函数 */
 
function ajax({type, dataType, async, data, url, success, fail}) {
  type = (type || "GET").toUpperCase();
  dataType = dataType || 'json';
  async = async || true;
  var getParams = function (data) { // 将对象拼接成字符串形式
    var arr = [];
    for (var param in data) {
      arr.push(encodeURIComponent(param) + '=' + encodeURIComponent(data[param]));
    }
    return arr.join('&');
  }
  var params = getParams(data),
  xhr;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveXObject('Microsoft.XMLHTTP')
  }
  xhr.onreadystatechange = function () {
    if (dataType === 'json') {
      if (xhr.readyState == 4) {
        var status = xhr.status;
        if (status >= 200 && status < 300) {
          success && success(xhr.responseText, xhr.responseXML); // 判断success回调函数的存在并执行函数
        } else {
          fail && fail(status); // 判断fail回调函数的存在并执行函数
        }
      }
    } else {
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        var oScript = document.createElement('script');
        document.body.appendChild(oScript);
        var callbackname = 'monoplasty'
        oScript.src = opt.url + "?" + params + '&callback=' + callbackname;
        window['monoplasty'] = function (data) {
          success(data);
          document.body.removeChild(oScript);
        };
      }
    }
  };
  if (type == 'GET') {
    xhr.open("GET", url + '?' + params, async);
    xhr.send(null);
  } else if (type == 'POST') {
    xhr.open('POST', url, async);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(params);
  }
}
 

 

【调用示例】

ajax({    url: "",     type: 'GET',     data: {        name: 'monoplasty',        age: '23',        email: 'monoplasty@aliyun.com'    },    success: function(response, xml) {        console.log(response);     },    fail: function(status) {        console.log('状态码为' + status);     }});

 

【参考地址】https://blog.csdn.net/monoplasty/article/details/80315147

 

转载于:https://www.cnblogs.com/wannananana/p/11338313.html

你可能感兴趣的文章
hdu 2058 The sum problem
查看>>
[wp7游戏]wp7~~X-Box Live游戏~~集合贴~~
查看>>
Access 标准表达式中数据类型不匹配问题
查看>>
Python实现屏幕截图
查看>>
【Python求助】在eclipse和pycharm中,通过adb install安装中文名字APK时老是报错,如何解决...
查看>>
用weka来做Logistic Regression
查看>>
Linux现学现用之Top命令
查看>>
[C3W1] Structuring Machine Learning Projects - ML Strategy 1
查看>>
【原创】谈谈服务雪崩、降级与熔断
查看>>
Java加密代码 转换成Net版
查看>>
jquery.validation.js 使用
查看>>
day38 mycql 初识概念,库(增删改查),表(增删改)以及表字段(增删改查),插入更新操作...
查看>>
数据库高级查询
查看>>
C语言实现封装、继承和多态
查看>>
Linux字符设备驱动框架(二):Linux内核的LED设备驱动框架
查看>>
创建文件
查看>>
Nginx 相关介绍
查看>>
leetcode[33]Search in Rotated Sorted Array
查看>>
安卓上按钮绑定监听事件的两种写法
查看>>
OpenCV Shi-Tomasi角点检测子
查看>>