成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

關(guān)于Ajax的封裝詳解

瀏覽:31日期:2022-06-14 13:44:42
目錄Ajax的封裝一、最簡單的原生Ajax封裝二、使用promise函數(shù)封裝三、promise配合async和await使用四、使用axios工具庫直接發(fā)送AjaxAjax的封裝

一個(gè)免費(fèi)的測試接口

https://api.apiopen.top/getJoke

一、最簡單的原生Ajax封裝先看下效果

具體代碼<body> <div class='box'><button id='btn'>來段數(shù)據(jù)</button><br> <textarea ></textarea> </div> <script>const btn = document.getElementById('btn');const txt = document.getElementById('text');btn.onclick = function(){ getAjax('get','https://api.apiopen.top/getJoke',function(res){let narr=[];for(let i=0;i<res.length;i++){ narr.push('\n'+(i+1)+'.'+res[i].text) console.log(res[i].text); text.innerHTML=narr;} });}function getAjax(method,url,callback){ const xhr = new XMLHttpRequest(); xhr.open(method,url); xhr.send(); xhr.onreadystatechange = function(){if(xhr.readyState === 4){ if(xhr.status>=200 && xhr.status<300){const res = JSON.parse(xhr.response);callback(res.result); }} }} </script>二、使用promise函數(shù)封裝

Promise是ES6引入的異步編程的新解決方案,語法上Promise是一個(gè)構(gòu)造函數(shù),用來封裝異步操作并可以獲取其成功或者失敗的回調(diào)結(jié)果。

通過promise實(shí)例化的對象可以接受一個(gè)參數(shù),參數(shù)類型為函數(shù),該函數(shù)的兩個(gè)參數(shù)是resolve和reject,在請求到數(shù)據(jù)后可以通過resolve、resolve函數(shù)來改變Promise對象的狀態(tài)resolve表示成功,resolve表示失敗成功或者失敗都可以調(diào)用Promise對象的then方法then接收兩個(gè)參數(shù),兩個(gè)參數(shù)都是函數(shù)類型成功的形參為value,失敗的形參為reasonvalue就是resolve方法里的返回結(jié)果<script> const btn = document.getElementById('btn'); btn.onclick = function(){grtAjax('get','https://api.apiopen.top/getJoke',function(res){ console.log(res);}); } function grtAjax(method,url,callback){const p = new Promise((resolve,reject)=>{ const xhr = new XMLHttpRequest(); xhr.open(method,url); xhr.send(); xhr.onreadystatechange = function(){if(xhr.readyState == 4){ if(xhr.status >= 200 && xhr.status < 300){resolve(xhr.response); }else{reject(xhr.status); }} }});p.then(function(value){ const res = JSON.parse(value); callback(res.result)},function(reason){console.error(reason);}) }</script>

三、promise配合async和await使用

async

async和await兩種語法結(jié)合可以讓異步代碼像同步代碼一樣async函數(shù)的返回值為promise對象該promise對象的結(jié)果是由async函數(shù)執(zhí)行的返回值決定的只要返回值的類型不是一個(gè)promise類型的對象則async函數(shù)的返回結(jié)果就是一個(gè)成功的promise對象返回值的類型不是一個(gè)promise類型的對象則跟promise對象的狀態(tài)有關(guān)revolve或者reject或者拋出異常

await

await右側(cè)的表達(dá)式一般為promise對象,但也可以是其他的值如果是promise對象,await返回的是promise成功的值如果是其他的值,直接將此值作為await的返回值await必須寫在async函數(shù)中,但是async函數(shù)中可以沒有await如果await的promise狀態(tài)是失敗的,就會(huì)拋出異常,需要通過try…catch捕獲處理

<body> <button>請求數(shù)據(jù)</button> <script>const btn = document.querySelector('button');function sendAjax(method,url){ return new Promise((resolve,reject)=>{ const xhr = new XMLHttpRequest();xhr.responseType = 'json';xhr.open(method,url);xhr.send();xhr.onreadystatechange = function(){ if(xhr.readyState === 4){if(xhr.status >=200 && xhr.status<300){ resolve(xhr.response);}else{ reject(xhr.status);} }} })}btn.addEventListener('click',async function(){ let result = await sendAjax('get','https://api.apiopen.top/getJoke'); console.log(result);}) </script></body>四、使用axios工具庫直接發(fā)送Ajax

Axios 是一個(gè)基于 promise 網(wǎng)絡(luò)請求庫,作用于node.js 和瀏覽器中。 它是 isomorphic 的(即同一套代碼可以運(yùn)行在瀏覽器和node.js中)。在服務(wù)端它使用原生 node.js http 模塊, 而在客戶端 (瀏覽端) 則使用 XMLHttpRequests。

這里使用了vue-cli搭建了一個(gè)vue項(xiàng)目并下載了 axios

post

get

<template><div><button @click='post'>直接發(fā)送POST</button><button @click='get'>直接發(fā)送GET</button> </div></template><script>export default { data(){ return{} }, methods:{ async get(){ const {data:res} = await this.$axios.get('https://api.apiopen.top/getJoke',{params:{id:1} }); console.log(res); }, post(){ this.$axios.post('https://api.apiopen.top/getJoke',{name:'yxj',gender:'男'}) .then((res)=>{console.log(res.data.result); }); } }}</script>

到此這篇關(guān)于關(guān)于Ajax的封裝詳解的文章就介紹到這了,更多相關(guān)Ajax的封裝內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Ajax
相關(guān)文章: