100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 原生js封装http请求 get post请求

原生js封装http请求 get post请求

时间:2024-05-14 09:16:17

相关推荐

原生js封装http请求 get post请求

let origin = '' // 后端接口域名const address = {// info: origin + '/template/getinfo', // 后端接口}export default function httpApi(type, _url, params = {}) {let object = {method: type || 'GET', // 请求类型url: address[_url],// 请求链接data: params// 参数}return httpRequest(object)}export function httpRequest(obj, successfun, errFun){return new Promise((resolve, reject) => {var xmlHttp = null;//创建 XMLHttpRequest 对象,老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")if(window.XMLHttpRequest){//code for all new browsers()xmlHttp = new XMLHttpRequest;}else if(window.ActiveXObject){//code for IE5 and IE6xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}//判断是否支持请求if(xmlHttp == null){alert("浏览器不支持xmlHttp");return;}//请求方式, 转换为大写var httpMethod = (obj.method || "Get").toUpperCase();//数据类型var httpDataType = obj.dataType || 'json';//urlvar httpUrl = obj.url;//异步请求var async = true;//post请求时参数处理if(httpMethod == "POST"){//请求体中的参数 post请求参数格式为:param1=test&param2=test2var data = obj.data || {};console.log(obj.data)var requestData = '';for(var key in data){requestData = requestData + key + "=" + data[key] + "&";}if(requestData == ''){requestData = '';}else{requestData = requestData.substring(0, requestData.length - 1);}}//请求接口if(httpMethod == 'GET'){xmlHttp.open("GET", httpUrl, async);xmlHttp.send(null);}else if(httpMethod == "POST"){xmlHttp.open("POST", httpUrl, async);xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");xmlHttp.send(requestData);}//onreadystatechange 是一个事件句柄。它的值 (state_Change) 是一个函数的名称,当 XMLHttpRequest 对象的状态发生改变时,会触发此函数。状态从 0 (uninitialized) 到 4 (complete) 进行变化。仅在状态为 4 时,我们才执行代码xmlHttp.onreadystatechange = function(){//completeif(xmlHttp.readyState == 4){// 此处用了promise替代了请求成功后的回调if(xmlHttp.status == 200){let res = JSON.parse(xmlHttp.responseText);if (res && res.errno == 0) {resolve(res);} else {reject(res);}//请求成功执行的回调函数// successfun(JSON.parse(xmlHttp.responseText));} else {//请求失败的回调函数errFun;}}}})}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。