XHR 介绍及实践

发布于:2025-08-31 ⋅ 阅读:(27) ⋅ 点赞:(0)

What is it?

XML(XMLHttpRequest) 是浏览器提供的一种用于前端页面和后端服务器进行异步通信的编程接口。它允许在不重新加载整个页面的情况下,与服务器交换数据并更新部分页面内容,是 AJAX 技术的核心。

What is it used for?

  • 异步请求:在不阻塞页面渲染的情况下,向服务器发送请求并接收响应。
  • 局部更新:获取数据后,通过 JavaScript 更新页面部分内容。
  • 数据交互:支持多种数据格式(XML、JSON、表单数据等)的发送和接收。

How to use it?

<!DOCTYPE html>
<html>
<head>
  <meta charset="uft-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>XHR 实践案例</title>
  <style>
    body {
      font-family: Arial, Helvetica, sans-serif;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
    }
    .container {
      text-align: center;
      padding: 20px;
    }
    button {
      padding: 10px 20px;
      font-size: 16px;
      cursor: pointer;
      background-color: green;
      color: white;
      border: none;
      border-radius: 5px;
    }
    button:hover {
      background-color: aquamarine;
    }
    .user-data {
      margin-top: 20px;
      padding: 20px;
      border: 1px solid red;
      border-radius: 5px;
      display: none;
    }
    .error {
      color: red;
      margin-top: 20px;
      display: none;
    }
    .loading {
      margin-top: 20px;
      display: none;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>用户数据查询</h1>
    <button id="fetchUserBtn">获取用户信息</button>
    <div class="loading" id="loading">加载中...</div>
    <div class="user-data" id="userData"></div>
    <div class="error" id="errorMsg"></div>
  </div>

  <script>
    // 获取 DOM 元素
    const fetchBtn = document.getElementById('fetchUserBtn');
    const userDataDiv = document.getElementById('userData');
    const errorMsgDiv = document.getElementById('errorMsg');
    const loadingDiv = document.getElementById('loading');

    // 绑定按钮点击事件
    fetchBtn.addEventListener('click', fetchUserData);

    // 使用 XMLHttpRequest 对象获取用户数据
    function fetchUserData() {
      // 重置状态
      userDataDiv.style.display = 'none';
      errorMsgDiv.style.display = 'none';
      loadingDiv.style.display = 'block';
      // 1. 创建 XMLHttpRequest 对象
      const xhr = new XMLHttpRequest();

      // 2. 配置一个 get 请求
      xhr.open('GET', 'https://jsonplaceholder.typicode.com/users/1');

      // 3. 设置请求头 (可选,get 请求通常不需要)
      xhr.setRequestHeader('Content-Type', 'application/json');

      // 4. 监听请求状态的变化
      xhr.onreadystatechange = function() {
        // readyState 的值为4表示请求完成
        if (xhr.readyState === 4) {
          // 隐藏 loading 元素
          loadingDiv.style.display = 'none';
          // 判断请求是否成功
          if (xhr.status === 200) {
            // 显示用户数据
            const user = JSON.parse(xhr.responseText);
            displayUserData(user);
          } else {
            // 显示错误信息
            showErrorMsg('获取用户信息失败,请检查网络连接');
          }
        }
      };

      // 监听网络错误
      xhr.onerror = function() {
        loadingDiv.style.display = 'none';
        showErrorMsg('网络错误,请检查网络连接');
      };

      // 设置超时时间
      xhr.timeout = 5000;
      xhr.ontimeout = function() {
        loadingDiv.style.display = 'none';
        showErrorMsg('请求超时,请检查网络连接');
      }

      // 5. 发送请求,get 请求不需要请求体
      xhr.send(null);
    }

    // 显示用户数据
    function displayUserData(user) {

      userDataDiv.innerHTML = `
        <h2>用户信息</h2>
        <p>ID: ${user.id}</p>
        <p>名字: ${user.name}</p>
        <p>邮箱: ${user.email}</p>
        <p>电话: ${user.phone}</p>
        <p>地址: ${user.address.street}, ${user.address.suite}, ${user.address.city}, ${user.address.zipcode}</p>
        <p>公司: ${user.company.name}, ${user.company.catchPhrase}, ${user.company.bs}</p>
      `;
      userDataDiv.style.display = 'block';
    }
    // 显示错误信息
    function showErrorMsg(msg) {
      errorMsgDiv.innerHTML = msg;
      errorMsgDiv.style.display = 'block';
    }
  </script>
</body>

</html>

网站公告

今日签到

点亮在社区的每一天
去签到