promise封装ajax
生活随笔
收集整理的這篇文章主要介紹了
promise封装ajax
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
const axios = function(options){let promise = new promise(( resolve , reject )=>{var xhr = null;if(window.XMLHttpRequest){//兼容處理xhr = new XMLHttpRequest();}else{xhr = new ActiveXObject("Microsoft.XMLHTTP"); }var data = "";for (var key in options.data) {//數(shù)據(jù)處理data += "&" + key + "=" + options.data[key]}if (options.method == "get") {let url = options.url + "?" + data.slice(1);xhr.open(options.method, url);xhr.send();} else if (options.method == "post") {xhr.open(options.method, options.url);xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");xhr.send(data);}xhr.onreadystatechange = function () {let timer = null;let timeout = options.timeout?options.timeout:5000 //等待響應(yīng)的時(shí)間 if(xhr.readyState == 4 && xhr.status == 200){let res = JSON.parse(xhr.responseText);clearTimeout(timer);resolve(res);}timer = setTimeout(()=>{clearTimeout(timer);reject(xhr.status);},timeout) }})return promise;
}
栗子:
axios({method:"get",url:"./data.json",data:{id:10}}).then((res)=>{console.log(res)},(e)=>{console.log(e);})?
轉(zhuǎn)載于:https://www.cnblogs.com/wildccy/p/10543154.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的promise封装ajax的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 牛客练习赛42 A字符串
- 下一篇: Linux wildcard