您的位置:首頁技術文章
文章詳情頁

關于Ajax的封裝詳解

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

一個免費的測試接口

https://api.apiopen.top/getJoke

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

具體代碼<body> <div class='box'><button id='btn'>來段數據</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函數封裝

Promise是ES6引入的異步編程的新解決方案,語法上Promise是一個構造函數,用來封裝異步操作并可以獲取其成功或者失敗的回調結果。

通過promise實例化的對象可以接受一個參數,參數類型為函數,該函數的兩個參數是resolve和reject,在請求到數據后可以通過resolve、resolve函數來改變Promise對象的狀態resolve表示成功,resolve表示失敗成功或者失敗都可以調用Promise對象的then方法then接收兩個參數,兩個參數都是函數類型成功的形參為value,失敗的形參為reasonvalue就是resolve方法里的返回結果<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兩種語法結合可以讓異步代碼像同步代碼一樣async函數的返回值為promise對象該promise對象的結果是由async函數執行的返回值決定的只要返回值的類型不是一個promise類型的對象則async函數的返回結果就是一個成功的promise對象返回值的類型不是一個promise類型的對象則跟promise對象的狀態有關revolve或者reject或者拋出異常

await

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

<body> <button>請求數據</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工具庫直接發送Ajax

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

這里使用了vue-cli搭建了一個vue項目并下載了 axios

post

get

<template><div><button @click='post'>直接發送POST</button><button @click='get'>直接發送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>

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

標簽: Ajax
相關文章:
国产综合久久一区二区三区