axios基本用法
axios.defaults.baseURL='https://d18c4217.cn' async function aaa(){ const a = await axios.get('/fictionSelect.php'); return a } aaa().then(a=>{ console.log(a) })
promise基本用法
<script type="text/javascript"> const i=new Promise(function(resolve,reject){ setTimeout(()=>{ const flag=false; if(!flag){ resolve('成功') }else{ reject('失败') } },1000) }) i.then(data=>{ console.log(data)//成功 }) </script>
promise创建ajax
function promise(url){ var p=new Promise(function(resolve,reject){ var xhr=new XMLHttpRequest() xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ resolve(xhr.responseText) }else{ reject('请求出错') } } } xhr.open('post',url) xhr.send(null) }) return p } promise('http://v.juhe.cn/joke/randJoke.php?key=886be12054b5d84dbab2f01eab08ac8b') .then(res=>{ const data=JSON.parse(res) })
Ajax函数封装
// Ajax封装 function ajax(url,callback){ var xhr=new XMLHttpRequest() xhr.open('get',url) xhr.send() xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ callback(xhr.responseText) }else{ return console.log('请求失败') } } } } //回调函数,ajax异步有一个过程, //consloe的时候可能ajax过程还没好 //这时consloe了就会undefine