欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2023年05月17日 10:31:49   作者:獨(dú)立寒秋-  
這篇文章主要介紹了關(guān)于Ajax的封裝詳解,ajax用于瀏覽器與服務(wù)器之間使用異步數(shù)據(jù)傳輸(HTTP 請(qǐng)求),做到局部請(qǐng)求以實(shí)現(xiàn)局部刷新,本篇講解ajax的封裝,需要的朋友可以參考下

Ajax的封裝

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

https://api.apiopen.top/getJoke

一、最簡(jiǎn)單的原生Ajax封裝

  • 先看下效果

在這里插入圖片描述

  • 具體代碼
<body>
    <div class="box">
        <button id="btn">來(lái)段數(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引入的異步編程的新解決方案,語(yǔ)法上Promise是一個(gè)構(gòu)造函數(shù),用來(lái)封裝異步操作并可以獲取其成功或者失敗的回調(diào)結(jié)果。

  • 通過(guò)promise實(shí)例化的對(duì)象可以接受一個(gè)參數(shù),參數(shù)類型為函數(shù),該函數(shù)的兩個(gè)參數(shù)是resolve和reject,
  • 在請(qǐng)求到數(shù)據(jù)后可以通過(guò)resolve、resolve函數(shù)來(lái)改變Promise對(duì)象的狀態(tài)
  • resolve表示成功,resolve表示失敗
  • 成功或者失敗都可以調(diào)用Promise對(duì)象的then方法
  • then接收兩個(gè)參數(shù),兩個(gè)參數(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兩種語(yǔ)法結(jié)合可以讓異步代碼像同步代碼一樣
  • async函數(shù)的返回值為promise對(duì)象
  • 該promise對(duì)象的結(jié)果是由async函數(shù)執(zhí)行的返回值決定的
  • 只要返回值的類型不是一個(gè)promise類型的對(duì)象則async函數(shù)的返回結(jié)果就是一個(gè)成功的promise對(duì)象
  • 返回值的類型不是一個(gè)promise類型的對(duì)象則跟promise對(duì)象的狀態(tài)有關(guān)revolve或者reject或者拋出異常

await

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

在這里插入圖片描述

<body>
    <button>請(qǐng)求數(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工具庫(kù)直接發(fā)送Ajax

Axios 是一個(gè)基于 promise 網(wǎng)絡(luò)請(qǐng)求庫(kù),作用于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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論