温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么封装一个Ajax函数

发布时间:2021-05-07 10:05:47 来源:亿速云 阅读:168 作者:小新 栏目:开发技术

这篇文章将为大家详细讲解有关怎么封装一个Ajax函数,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

如何封装Ajax函数

一个Ajax函数:

// 一个Ajax函数 var xhr = null; if(window.XMLHttpRequest){    xhr = new XMLHttpRequest; }else{    xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("GET","https://jsonplaceholder.typicode.com/users"); xhr.send(null); xhr.onreadystatechange = function(){    if(this.readyState === 4){         console.log(xhr.responseText)     } }

封装自己的 Ajax 函数

参数1:{string} 请求方法--method
参数2:{string} 请求地址--url
参数3:{object} 请求参数--params
参数4:{function} 请求完成后,执行的回调函数--done

 function ajax(method,url,params,done){ //  统一将method方法中的字母转成大写,后面判断GET方法时 就简单点   method = method.toUpperCase();    //IE6的兼容   var xhr = window.XMLHttpRequest    ? new XMLHttpRequest()    : new ActiveXObject("Microsoft.XMLHTTP");   //创建打开一个连接 open                 //将对象格式的参数转为urlencoded模式   //新建一个数组,使用for循环,将对象格式的参数,   //以(id = 1)的形式,每一个键值对用 & 符号连接  var pairs = [];  for(var k in params){      pairs.push(k + "=" + params[k]);   }   var str = pairs.join("&");          //判断是否是get方法 , get方法的话,需要更改url的值  if(method == "GET"){        url += "?" + str;   }               //创建打开一个连接  xhr.open(method,url); var data = null; if(method == "POST"){     //post方法 还需要设置请求头、请求体     xhr.setRequestHeader("Content-Type",     "application/x-www-form-urlencoded");     data = str;                   } xhr.send(data);  //执行回调函数 xhr.onreadystatechange = function(){    if(this.readyState == 4) {        done(JSON.parse(this.responseText));    }return;    // 执行外部传进来的回调函数即可    // 需要用到响应体    } }   //调用函数 //get方法 //  ajax("GET","http://localhost:3000/users", //     {"id":1}, //     function(data){ //         console.log(data); //  }); //post方法      ajax("POST", "http://localhost:3000/users",  { "name": "lucky","class":2,"age":20 },  function (data) {      console.log(data); });

关于“怎么封装一个Ajax函数”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI