前端请求中ajax 和 xhr 是什么关系

文章类型:Javascript

发布者:hp

发布时间:2024-11-28

一:概述

在前端开发中,网络请求是必不可少的技能之一。网络请求可以让我们与服务器交换数据,实现各种功能和效果。现在,各种各样的请求库层次不穷,那么,最开始的xhr和ajax他们有什么不同

二:区别

(一)定义

1:Ajax(异步 JavaScript 和 XML),是一种在不重新加载整个网页的情况下,与服务器进行数据交换并更新部分网页内容的技术方法

2:XMLHttpRequest (XHR)是一个 JavaScript 对象,它可以用来向服务器发送 HTTP 请求,从而实现网页的局部更新。是 AJAX 编程的核心技术

(二)特点:

1:Ajax

浏览器内置的XMLHttpRequest对象(向服务器请求数据)

JavaScript和HTML DOM(显示或使用数据)

XML、JSON或纯文本(作为数据传输格式)


2:XMLHttpRequest

不重新加载页面的情况下更新网页 在页面已加载后从服务器请求/接收数据 在后台向服务器发送数据

使用繁琐,需要设置很多值,还需要考虑兼容代码

三:代码

1:Ajax

const httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
  //判断请求是否完成(readyState为4)并且成功(status为200)
  if (httpRequest.readyState === 4 && httpRequest.status === 200) {
    //在这里处理返回的数据,比如显示在网页上
    console.log(httpRequest.responseText);
  }
};
httpRequest.open("GET", "https://www.cqhxb.com/api/data");
httpRequest.send();

2:XMLHttpRequest

if (window.XMLHttpRequest) { // model browser
  xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) { // IE 6 and older
  xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
xhr.open('POST', url, true)
xhr.send(data)
xhr.onreadystatechange = function () {
  try {
    // TODO 处理响应
    if (xhr.readyState === XMLHttpRequest.DONE) {
      // XMLHttpRequest.DONE 对应值是 4
      // Everything is good, the response was received.
      if (xhr.status === 200) {
        // Perfect!
      } else {
        // There was a problem with the request.
        // For example, the response may hava a 404 (Not Found)
        // or 500 (Internal Server Error) response code.
      }
    } else {
      // Not ready yet
    }
  } catch (e) {
    // 通信错误的事件中(例如服务器宕机)
    alert('Caught Exception: ' + e.description)
  }
}

四:拓展

1:fetch,现代浏览器提供更简洁的异步请求方式,基于Promise

fetch("https://www.cqhxb.com/data")
  .then((response) => response.json())

  .then((data) => console.log(data))

  .catch((error) => console.error(error));

2:Axios,三方Ajax库,提供了简洁的接口

axios
  .get("https://www.cqhxb.com/data")

  .then((response) => console.log(response.data))

  .catch((error) => console.error(error));

3:jQuery 的 $.ajax() 方法

$.ajax({
  url: "https://www.cqhxb.com/data",

  method: "GET",

  success: function (data) {
    console.log(data);
  },

  error: function (error) {
    console.error(error);
  },
});

五:总结

1:XMLHttpRequest (XHR)是一个 JavaScript 对象,是实现 Ajax 技术的底层机制或工具、关键对象之一,用来向服务器发送 HTTP 请求,从而实现网页的局部更新。

2:AJAX 代表异步的 JavaScript 和 XML,使用 XMLHttpRequest(XHR)对象与服务器通信。