第六篇 手写原理代码 - 对象 【 实现 AJAX 请求 】

AJAX 是 Asynchronous JavaScript and XML 的缩写,指的是通过 JavaScript 和 XML 技术在不重新加载整个页面的情况下,实现与服务器之间异步通信的技术。使用 AJAX 技术能够使网页更加动态和用户友好。

JavaScript 的 AJAX 技术借助于浏览器内置的 XMLHttpRequest 对象实现。XMLHttpRequest 对象是一个用于从 web 服务器获取数据的 API。使用 AJAX 技术,我们可以通过 XMLHttpRequest 发送请求,接收服务器返回的数据,并根据需要更新网页中的部分内容,而无需刷新整个页面。这种方式对于提高网站的性能和用户体验非常有帮助

总之,AJAX 是 JavaScript 中一种异步通信技术,通过 XMLHttpRequest 对象实现。使用 AJAX 技术能够使网页更加动态和用户友好

实现一个 AJAX 请求

const ajax = {
  get(url, sucess, data = null, fail) {
    const xhr = new XMLHttpRequest(); //
    xhr.open("GET", url, true); // true 是否异步
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
          sucess(xhr.responseText);
        } else {
          fail(xhr.responseText);
        }
      }
    };
    xhr.send(data);
  },

  post(url, data = null, success, fail) {
    const xhr = new XMLHttpRequest(); // new 一个请求对象
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
          success(xhr.responseText);
        } else {
          fail(xhr.responseText);
        }
      }
    };
    xhr.send(data);
  },
};
posted @ 2023-04-11 23:10  caix-1987  阅读(25)  评论(0)    收藏  举报