關(guān)于Ajax的封裝詳解
Ajax的封裝
一個免費的測試接口
https://api.apiopen.top/getJoke
一、最簡單的原生Ajax封裝
- 先看下效果
- 具體代碼
<body> <div class="box"> <button id="btn">來段數(shù)據(jù)</button><br> <textarea id="text" ></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òu)造函數(shù),用來封裝異步操作并可以獲取其成功或者失敗的回調(diào)結(jié)果。
- 通過promise實例化的對象可以接受一個參數(shù),參數(shù)類型為函數(shù),該函數(shù)的兩個參數(shù)是resolve和reject,
- 在請求到數(shù)據(jù)后可以通過resolve、resolve函數(shù)來改變Promise對象的狀態(tài)
- resolve表示成功,resolve表示失敗
- 成功或者失敗都可以調(diào)用Promise對象的then方法
- then接收兩個參數(shù),兩個參數(shù)都是函數(shù)類型
- 成功的形參為value,失敗的形參為reason
- value就是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í)行的返回值決定的
- 只要返回值的類型不是一個promise類型的對象則async函數(shù)的返回結(jié)果就是一個成功的promise對象
- 返回值的類型不是一個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)是失敗的,就會拋出異常,需要通過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 是一個基于 promise 網(wǎng)絡(luò)請求庫,作用于node.js 和瀏覽器中。 它是 isomorphic 的(即同一套代碼可以運行在瀏覽器和node.js中)。在服務(wù)端它使用原生 node.js http
模塊, 而在客戶端 (瀏覽端) 則使用 XMLHttpRequests。
- 這里使用了vue-cli搭建了一個vue項目并下載了 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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React+ajax+java實現(xiàn)上傳圖片并預(yù)覽功能
這篇文章主要介紹了React+ajax+java實現(xiàn)上傳圖片并預(yù)覽功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05Ajax登陸使用Spring Security緩存跳轉(zhuǎn)到登陸前的鏈接
這篇文章主要介紹了Ajax登陸使用Spring Security緩存跳轉(zhuǎn)到登陸前的鏈接,需要的朋友可以參考下2019-04-04