Ajax封装

Ajax简介及基础在上篇博客已经介绍这里不再赘述

一、最简单原生Ajax封装

在这里插入图片描述

<body>
    <div class="box">
        &lt;button id="btn"&gt;来段数据&lt;/button&gt;<br&gt;
    <textarea  id="text" &gt;</textarea&gt;
    </div&gt;
    <script&gt;
        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 &amp;&amp; xhr.status<300){
                        const res = JSON.parse(xhr.response);
                        callback(res.result);
                    }
                }
            }
        }
    </script>

二、使用promise函数封装

Promise是ES6引入异步编程的新解决方案语法上Promise是一个构造函数用来封装异步操作可以获取其成功或者失败回调结果

<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 &amp;&amp; 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配合asyncawait使用

async

await

在这里插入图片描述

<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 &amp;&amp; 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

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>

原文地址:https://blog.csdn.net/weixin_51445423/article/details/124332172

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_35168.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注