Ajax介绍以及实例

Ajax详细概念介绍:Ajax请求的五个步骤_谁是听故事的人的博客-CSDN博客_ajax请求的五个步骤

一、初始的Ajax实例

其实Ajax就五大步:

  1. 创建XMLHttpRequest对象,即创建一个异步调用对象.
  2. 创建一个新的HTTP请求,并指定该HTTP请求的方法、URL及验证信息.
  3. 设置响应HTTP请求状态变化的函数.
  4. 发送HTTP请求.
  5. 获取异步调用返回的数据.

下面是实例:


		// 创建XMLHttpRequest对象,即一个用于保存异步调用对象的变量
        let  xmlHttpRequest = new XMLHttpRequest();
        xmlHttpRequest.open("GET",url); // 创建http请求
		xmlHttpRequest.onreadystatechange=function(){ // 设置响应http请求状态变化的事件
            console.log('请求过程', xmlHttpRequest.readyState);
			if(xmlHttpRequest.readyState == 4){ // 判断异步调用是否成功,若成功开始局部更新数据
				console.log('状态码为', xmlHttpRequest.status);
				if(xmlHttpRequest.status == 200) {
					console.log(xmlHttpRequest .response); // 得到的请求的结果
				} else { // 如果异步调用未成功,弹出警告框,并显示错误状态码
					alert("error:HTTP状态码为:"+xmlHttpRequest.status);
				}
			}
		}
        xmlHttpRequest.send(); // 发送请求

二、利用promise封装Ajax

function getJSON(url){
    return new Promise((resolve,reject)=>{
        const xhr=new XMLHttpRequest();
        xhr.open('GET',url);
        xhr.onreadystatechange=handler;
        xhr.responseType='json';
        xhr.setRequestHeader('Accept','application/json');
        xhr.send();
        function handler(){
            if (this.readyState == 4) {
                if (this.status == 200) {
                    resolve(this.response);                   
                }else{
                    reject(new Error(this.statusText))
                } 
            }
        }
    })
}

这里的优越之处是可以利用promise的实例then、catch方法,便于对数据的处理


getJSON(url).then(function(posts) {
  // 这里返回的posts就是请求返回的数据,可以在这进行处理
}).catch(function(error) {
  // 处理 getJSON 和 前一个回调函数运行时发生的错误
  console.log('发生错误!', error);
});

三、加入async封装Ajax

这里是采用是音乐播放器中的实例

const BASE_URL = `http://localhost:3000`;
console.log("ajax")
export default function Ajax({
  //请求参数配置
  method = "GET", //默认为'get'请求
  url,
  data = {},
}) {
  return new Promise((resolve) => {
    // 通过 Promise 返回异步请求
    const xhr = new XMLHttpRequest();
    xhr.open(method, BASE_URL + url);
    xhr.onload = function () {
      resolve(JSON.parse(xhr.response));
    };
    xhr.onerror = function () {
      // 待最后进行错误处理操作
      if (xhr.status == 0) {
      }
    };
    xhr.send(JSON.stringify(data));
  });
}

/**
 * @description: 获得轮播图信息
 * @param {*}
 * @return {*}
 */
export async function getBannerList() {
  const result = Ajax({
    url: `/homepage/block/page`,
  });
  return result;
}

在调用时,只用利用await调用即可

const result =await getBannerList();

 这时就直接获取了数据,再需要该数据时,直接引用即可。

这与前两种方法最大的区别是利用await的原理在模块其他模块调用时,更为方便,代码也更简洁。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时雨.`

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值