简体中文 繁體中文 English 日本語 Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français

站内搜索

搜索

活动公告

11-02 12:46
10-23 09:32
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31
10-23 09:28
通知:签到时间调整为每日4:00(东八区)
10-23 09:26

深入解析AJAX核心技术对象XMLHttpRequest的工作原理与应用场景

3万

主题

423

科技点

3万

积分

大区版主

木柜子打湿

积分
31916

三倍冰淇淋无人之境【一阶】财Doro小樱(小丑装)立华奏以外的星空【二阶】⑨的冰沙

发表于 2025-10-2 19:10:24 | 显示全部楼层 |阅读模式 [标记阅至此楼]

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

AJAX(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。它通过在后台与服务器进行少量数据交换,使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

在AJAX技术中,XMLHttpRequest(XHR)对象是核心。它是一个API,为客户端提供了在客户端和服务器之间传输数据的功能。它提供了一个简单的方式来获取URL上的数据,而无需刷新整个页面。这使得网页可以更新页面的局部内容,而不需要打断用户的操作。

XMLHttpRequest的历史和发展

XMLHttpRequest最初是由微软在1999年作为IE5.0的ActiveX对象引入的,随后其他浏览器厂商也实现了类似的功能。在2006年,W3C开始标准化XMLHttpRequest,使其成为Web标准。

XMLHttpRequest的发展经历了以下几个阶段:

1. 初期阶段(1999-2005):作为ActiveX对象在IE中实现,主要用于Outlook Web Access等应用。
2. 流行阶段(2005-2008):Google Maps、Gmail等应用的成功使AJAX技术流行起来。
3. 标准化阶段(2006-2014):W3C开始标准化XMLHttpRequest,使其成为Web标准。
4. 成熟阶段(2014至今):XMLHttpRequest Level 2规范发布,增加了许多新功能,如跨域请求、上传进度事件等。

XMLHttpRequest的工作原理

XMLHttpRequest的工作原理可以分为以下几个步骤:

1. 对象的创建

首先,需要创建一个XMLHttpRequest对象。在现代浏览器中,可以直接使用XMLHttpRequest构造函数:
  1. var xhr = new XMLHttpRequest();
复制代码

在旧版本的IE(IE5和IE6)中,需要使用ActiveX对象:
  1. var xhr = new ActiveXObject("Microsoft.XMLHTTP");
复制代码

为了兼容所有浏览器,通常会这样写:
  1. var xhr;
  2. if (window.XMLHttpRequest) {
  3.     // 现代浏览器
  4.     xhr = new XMLHttpRequest();
  5. } else if (window.ActiveXObject) {
  6.     // 旧版IE
  7.     xhr = new ActiveXObject("Microsoft.XMLHTTP");
  8. }
复制代码

2. 请求的发送

创建对象后,需要配置请求并发送。这包括设置请求的方法(GET、POST等)、URL、是否异步等:
  1. xhr.open('GET', 'https://api.example.com/data', true);
  2. xhr.send();
复制代码

open方法接受三个参数:

• method:HTTP请求方法,如”GET”、”POST”、”PUT”、”DELETE”等。
• url:请求的URL。
• async:一个布尔值,表示请求是否异步处理,默认为true。

对于POST请求,还可以设置请求头:
  1. xhr.open('POST', 'https://api.example.com/data', true);
  2. xhr.setRequestHeader('Content-Type', 'application/json');
  3. xhr.send(JSON.stringify({key: 'value'}));
复制代码

3. 状态的监听

XMLHttpRequest对象有一个readyState属性,表示请求/响应过程的当前活动阶段。这个属性的值从0到4变化:

• 0:未初始化(UNSENT)。已经创建了XMLHttpRequest对象,但尚未调用open()方法。
• 1:已打开(OPENED)。已经调用了open()方法,但尚未调用send()方法。
• 2:已发送(HEADERS_RECEIVED)。已经调用了send()方法,且已经接收到响应头。
• 3:接收中(LOADING)。已经接收到部分响应体。
• 4:完成(DONE)。已经接收到全部响应数据,而且已经可以在客户端使用了。

可以通过onreadystatechange事件监听readyState的变化:
  1. xhr.onreadystatechange = function() {
  2.     if (xhr.readyState === 4) {
  3.         if (xhr.status === 200) {
  4.             console.log('请求成功');
  5.         } else {
  6.             console.log('请求失败');
  7.         }
  8.     }
  9. };
复制代码

4. 响应的处理

当请求完成(readyState为4)且成功(status为200)时,可以通过以下属性获取响应数据:

• responseText:作为字符串形式的响应数据。
• responseXML:作为XML文档形式的响应数据。
• response:作为ArrayBuffer、Blob、Document、JSON或字符串形式的响应数据,取决于responseType的值。
• status:HTTP状态码。
• statusText:HTTP状态说明。
  1. xhr.onreadystatechange = function() {
  2.     if (xhr.readyState === 4 && xhr.status === 200) {
  3.         var data = JSON.parse(xhr.responseText);
  4.         console.log(data);
  5.     }
  6. };
复制代码

XMLHttpRequest的API详解

属性

XMLHttpRequest对象有以下主要属性:

1. readyState:表示请求/响应过程的当前活动阶段,值为0-4。
2. status:HTTP状态码,如200表示成功,404表示未找到等。
3. statusText:HTTP状态说明,如”OK”、”Not Found”等。
4. responseText:作为字符串形式的响应数据。
5. responseXML:作为XML文档形式的响应数据。
6. response:作为ArrayBuffer、Blob、Document、JSON或字符串形式的响应数据,取决于responseType的值。
7. responseType:设置响应数据的类型,可以是”“(默认,文本)、”arraybuffer”、”blob”、”document”、”json”或”text”。
8. timeout:设置请求的超时时间(毫秒)。
9. withCredentials:一个布尔值,表示是否跨域请求应该发送证书(如cookies、HTTP认证和客户端SSL证明)。
10. upload:一个XMLHttpRequestUpload对象,表示上传进度。

方法

XMLHttpRequest对象有以下主要方法:

1. open(method, url, async, username, password):初始化一个请求。method:HTTP请求方法,如”GET”、”POST”等。url:请求的URL。async:一个布尔值,表示请求是否异步处理,默认为true。username和password:可选,用于认证的用户名和密码。
2. method:HTTP请求方法,如”GET”、”POST”等。
3. url:请求的URL。
4. async:一个布尔值,表示请求是否异步处理,默认为true。
5. username和password:可选,用于认证的用户名和密码。
6. send(data):发送请求。data:可选,要发送的数据。对于GET请求,通常为null;对于POST请求,可以是字符串、FormData、Blob等。
7. data:可选,要发送的数据。对于GET请求,通常为null;对于POST请求,可以是字符串、FormData、Blob等。
8. abort():中止请求。
9. setRequestHeader(header, value):设置HTTP请求头。header:要设置的请求头名称。value:要设置的请求头值。
10. header:要设置的请求头名称。
11. value:要设置的请求头值。
12. getResponseHeader(header):获取指定的响应头。header:要获取的响应头名称。
13. header:要获取的响应头名称。
14. getAllResponseHeaders():获取所有的响应头。
15. overrideMimeType(mime):重写服务器返回的MIME类型。

open(method, url, async, username, password):初始化一个请求。

• method:HTTP请求方法,如”GET”、”POST”等。
• url:请求的URL。
• async:一个布尔值,表示请求是否异步处理,默认为true。
• username和password:可选,用于认证的用户名和密码。

send(data):发送请求。

• data:可选,要发送的数据。对于GET请求,通常为null;对于POST请求,可以是字符串、FormData、Blob等。

abort():中止请求。

setRequestHeader(header, value):设置HTTP请求头。

• header:要设置的请求头名称。
• value:要设置的请求头值。

getResponseHeader(header):获取指定的响应头。

• header:要获取的响应头名称。

getAllResponseHeaders():获取所有的响应头。

overrideMimeType(mime):重写服务器返回的MIME类型。

事件

XMLHttpRequest对象支持以下事件:

1. onreadystatechange:当readyState属性改变时触发。
2. onloadstart:当请求开始时触发。
3. onprogress:当请求接收到数据时触发。
4. onabort:当请求被中止时触发。
5. onerror:当请求发生错误时触发。
6. onload:当请求成功完成时触发。
7. ontimeout:当请求超时时触发。
8. onloadend:当请求完成(无论成功或失败)时触发。

XMLHttpRequest的应用场景

数据获取

最常见的应用场景是从服务器获取数据,然后更新页面的部分内容。例如,获取用户信息:
  1. function getUserInfo(userId) {
  2.     var xhr = new XMLHttpRequest();
  3.     xhr.open('GET', '/api/users/' + userId, true);
  4.     xhr.onreadystatechange = function() {
  5.         if (xhr.readyState === 4 && xhr.status === 200) {
  6.             var user = JSON.parse(xhr.responseText);
  7.             document.getElementById('username').textContent = user.name;
  8.             document.getElementById('useremail').textContent = user.email;
  9.         }
  10.     };
  11.     xhr.send();
  12. }
  13. // 使用示例
  14. getUserInfo(123);
复制代码

表单提交

使用XMLHttpRequest提交表单,可以实现无刷新提交,提供更好的用户体验:
  1. function submitForm(formId) {
  2.     var form = document.getElementById(formId);
  3.     var formData = new FormData(form);
  4.    
  5.     var xhr = new XMLHttpRequest();
  6.     xhr.open('POST', form.action, true);
  7.     xhr.onreadystatechange = function() {
  8.         if (xhr.readyState === 4) {
  9.             if (xhr.status === 200) {
  10.                 var response = JSON.parse(xhr.responseText);
  11.                 if (response.success) {
  12.                     alert('提交成功!');
  13.                 } else {
  14.                     alert('提交失败:' + response.message);
  15.                 }
  16.             } else {
  17.                 alert('请求失败,状态码:' + xhr.status);
  18.             }
  19.         }
  20.     };
  21.     xhr.send(formData);
  22.     return false; // 阻止表单默认提交
  23. }
  24. // HTML表单
  25. /*
  26. <form id="myForm" action="/api/submit" onsubmit="return submitForm('myForm')">
  27.     <input type="text" name="username" placeholder="用户名">
  28.     <input type="password" name="password" placeholder="密码">
  29.     <button type="submit">提交</button>
  30. </form>
  31. */
复制代码

文件上传

XMLHttpRequest Level 2支持文件上传,并且可以显示上传进度:
  1. function uploadFile(file, url, progressCallback, successCallback, errorCallback) {
  2.     var formData = new FormData();
  3.     formData.append('file', file);
  4.    
  5.     var xhr = new XMLHttpRequest();
  6.     xhr.open('POST', url, true);
  7.    
  8.     // 上传进度
  9.     xhr.upload.onprogress = function(e) {
  10.         if (e.lengthComputable) {
  11.             var percent = Math.round((e.loaded / e.total) * 100);
  12.             progressCallback(percent);
  13.         }
  14.     };
  15.    
  16.     xhr.onreadystatechange = function() {
  17.         if (xhr.readyState === 4) {
  18.             if (xhr.status === 200) {
  19.                 successCallback(xhr.responseText);
  20.             } else {
  21.                 errorCallback(xhr.status, xhr.statusText);
  22.             }
  23.         }
  24.     };
  25.    
  26.     xhr.onerror = function() {
  27.         errorCallback(0, '请求失败');
  28.     };
  29.    
  30.     xhr.send(formData);
  31. }
  32. // 使用示例
  33. /*
  34. var fileInput = document.getElementById('fileInput');
  35. fileInput.addEventListener('change', function(e) {
  36.     var file = e.target.files[0];
  37.     if (file) {
  38.         uploadFile(
  39.             file,
  40.             '/api/upload',
  41.             function(percent) {
  42.                 console.log('上传进度:' + percent + '%');
  43.                 document.getElementById('progress').style.width = percent + '%';
  44.             },
  45.             function(response) {
  46.                 console.log('上传成功:' + response);
  47.             },
  48.             function(status, statusText) {
  49.                 console.log('上传失败:' + status + ' ' + statusText);
  50.             }
  51.         );
  52.     }
  53. });
  54. */
复制代码

实时数据更新

使用XMLHttpRequest可以实现实时数据更新,例如聊天应用、实时监控等:
  1. function startPolling(url, interval, callback) {
  2.     var xhr = new XMLHttpRequest();
  3.    
  4.     function poll() {
  5.         xhr.open('GET', url + '?t=' + new Date().getTime(), true);
  6.         xhr.onreadystatechange = function() {
  7.             if (xhr.readyState === 4 && xhr.status === 200) {
  8.                 var data = JSON.parse(xhr.responseText);
  9.                 callback(data);
  10.                 setTimeout(poll, interval);
  11.             }
  12.         };
  13.         xhr.send();
  14.     }
  15.    
  16.     poll();
  17. }
  18. // 使用示例:每5秒获取一次新消息
  19. /*
  20. startPolling('/api/messages', 5000, function(messages) {
  21.     var messagesContainer = document.getElementById('messages');
  22.     messagesContainer.innerHTML = '';
  23.     messages.forEach(function(message) {
  24.         var messageElement = document.createElement('div');
  25.         messageElement.textContent = message.user + ': ' + message.text;
  26.         messagesContainer.appendChild(messageElement);
  27.     });
  28. });
  29. */
复制代码

XMLHttpRequest与Fetch API的对比

Fetch API是现代浏览器中提供的一种新的网络请求API,它提供了一个更强大、更灵活的功能集。下面是XMLHttpRequest与Fetch API的对比:

语法对比

XMLHttpRequest:
  1. var xhr = new XMLHttpRequest();
  2. xhr.open('GET', 'https://api.example.com/data', true);
  3. xhr.onreadystatechange = function() {
  4.     if (xhr.readyState === 4 && xhr.status === 200) {
  5.         console.log(JSON.parse(xhr.responseText));
  6.     }
  7. };
  8. xhr.send();
复制代码

Fetch API:
  1. fetch('https://api.example.com/data')
  2.     .then(response => response.json())
  3.     .then(data => console.log(data))
  4.     .catch(error => console.error('Error:', error));
复制代码

功能对比

1. Promise支持:Fetch API基于Promise,使得异步操作更加简洁,避免了回调地狱。
2. 流支持:Fetch API支持流,可以逐步读取响应数据,对于大文件处理更加高效。
3. CORS:Fetch API对CORS的处理更加清晰和严格。
4. 默认设置:Fetch API默认不发送和接收cookies,需要设置credentials选项。
5. 错误处理:Fetch API不会为HTTP错误状态(如404、500)触发reject,只有网络错误才会触发reject。

兼容性对比

• XMLHttpRequest:支持所有浏览器,包括IE7+。
• Fetch API:不支持IE和旧版浏览器,但可以通过polyfill实现兼容。

选择建议

• 如果需要支持旧版浏览器,或者需要上传进度、超时控制等特定功能,可以选择XMLHttpRequest。
• 如果使用现代浏览器,且代码简洁性更重要,可以选择Fetch API。

XMLHttpRequest的最佳实践和注意事项

错误处理

良好的错误处理是使用XMLHttpRequest的重要部分:
  1. function makeRequest(url, method, data, successCallback, errorCallback) {
  2.     var xhr = new XMLHttpRequest();
  3.     xhr.open(method, url, true);
  4.    
  5.     xhr.onreadystatechange = function() {
  6.         if (xhr.readyState === 4) {
  7.             if (xhr.status >= 200 && xhr.status < 300) {
  8.                 successCallback(xhr.responseText);
  9.             } else {
  10.                 errorCallback(xhr.status, xhr.statusText);
  11.             }
  12.         }
  13.     };
  14.    
  15.     xhr.onerror = function() {
  16.         errorCallback(0, 'Network error');
  17.     };
  18.    
  19.     xhr.ontimeout = function() {
  20.         errorCallback(0, 'Request timeout');
  21.     };
  22.    
  23.     if (data) {
  24.         xhr.setRequestHeader('Content-Type', 'application/json');
  25.         xhr.send(JSON.stringify(data));
  26.     } else {
  27.         xhr.send();
  28.     }
  29. }
  30. // 使用示例
  31. /*
  32. makeRequest(
  33.     '/api/data',
  34.     'GET',
  35.     null,
  36.     function(response) {
  37.         console.log('Success:', response);
  38.     },
  39.     function(status, statusText) {
  40.         console.error('Error:', status, statusText);
  41.     }
  42. );
  43. */
复制代码

超时处理

设置请求超时可以避免长时间等待:
  1. function requestWithTimeout(url, timeout) {
  2.     return new Promise(function(resolve, reject) {
  3.         var xhr = new XMLHttpRequest();
  4.         xhr.open('GET', url, true);
  5.         xhr.timeout = timeout;
  6.         
  7.         xhr.onload = function() {
  8.             if (xhr.status >= 200 && xhr.status < 300) {
  9.                 resolve(xhr.responseText);
  10.             } else {
  11.                 reject(new Error(xhr.statusText));
  12.             }
  13.         };
  14.         
  15.         xhr.onerror = function() {
  16.             reject(new Error('Network error'));
  17.         };
  18.         
  19.         xhr.ontimeout = function() {
  20.             reject(new Error('Request timeout'));
  21.         };
  22.         
  23.         xhr.send();
  24.     });
  25. }
  26. // 使用示例
  27. /*
  28. requestWithTimeout('/api/data', 5000)
  29.     .then(function(response) {
  30.         console.log('Success:', response);
  31.     })
  32.     .catch(function(error) {
  33.         console.error('Error:', error.message);
  34.     });
  35. */
复制代码

跨域请求

XMLHttpRequest支持跨域请求,但需要服务器设置适当的CORS头:
  1. function makeCorsRequest(url) {
  2.     var xhr = new XMLHttpRequest();
  3.    
  4.     // 检查是否支持CORS
  5.     if ("withCredentials" in xhr) {
  6.         // 现代浏览器
  7.         xhr.open('GET', url, true);
  8.         xhr.withCredentials = true;
  9.     } else if (typeof XDomainRequest != "undefined") {
  10.         // IE8和IE9
  11.         xhr = new XDomainRequest();
  12.         xhr.open('GET', url);
  13.     } else {
  14.         // 不支持CORS
  15.         console.error('CORS not supported');
  16.         return;
  17.     }
  18.    
  19.     xhr.onload = function() {
  20.         console.log('Response:', xhr.responseText);
  21.     };
  22.    
  23.     xhr.onerror = function() {
  24.         console.error('Error making CORS request');
  25.     };
  26.    
  27.     xhr.send();
  28. }
  29. // 使用示例
  30. // makeCorsRequest('https://api.example.com/data');
复制代码

缓存控制

为了避免缓存问题,可以在URL中添加时间戳或随机数:
  1. function makeRequestWithoutCache(url) {
  2.     var xhr = new XMLHttpRequest();
  3.     // 添加时间戳避免缓存
  4.     var timestamp = new Date().getTime();
  5.     xhr.open('GET', url + '?t=' + timestamp, true);
  6.    
  7.     xhr.onreadystatechange = function() {
  8.         if (xhr.readyState === 4 && xhr.status === 200) {
  9.             console.log(xhr.responseText);
  10.         }
  11.     };
  12.    
  13.     xhr.send();
  14. }
  15. // 使用示例
  16. // makeRequestWithoutCache('/api/data');
复制代码

实际代码示例

下面是一个完整的示例,展示如何使用XMLHttpRequest创建一个简单的天气应用:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Weather App</title>
  7.     <style>
  8.         body {
  9.             font-family: Arial, sans-serif;
  10.             max-width: 600px;
  11.             margin: 0 auto;
  12.             padding: 20px;
  13.         }
  14.         .weather-container {
  15.             border: 1px solid #ddd;
  16.             border-radius: 5px;
  17.             padding: 20px;
  18.             margin-top: 20px;
  19.         }
  20.         .loading {
  21.             display: none;
  22.             text-align: center;
  23.             margin: 20px 0;
  24.         }
  25.         .error {
  26.             color: red;
  27.             display: none;
  28.             margin: 20px 0;
  29.         }
  30.         .weather-info {
  31.             display: none;
  32.         }
  33.         .weather-info h2 {
  34.             margin-top: 0;
  35.         }
  36.         .weather-icon {
  37.             width: 100px;
  38.             height: 100px;
  39.             float: right;
  40.         }
  41.         .temperature {
  42.             font-size: 24px;
  43.             font-weight: bold;
  44.         }
  45.         .description {
  46.             text-transform: capitalize;
  47.             margin: 10px 0;
  48.         }
  49.         .details {
  50.             margin-top: 20px;
  51.         }
  52.         .details div {
  53.             margin: 5px 0;
  54.         }
  55.     </style>
  56. </head>
  57. <body>
  58.     <h1>Weather App</h1>
  59.     <div>
  60.         <input type="text" id="cityInput" placeholder="Enter city name">
  61.         <button id="searchButton">Search</button>
  62.     </div>
  63.    
  64.     <div class="loading" id="loading">Loading...</div>
  65.     <div class="error" id="error"></div>
  66.    
  67.     <div class="weather-container" id="weatherContainer" style="display: none;">
  68.         <div class="weather-info" id="weatherInfo">
  69.             <img class="weather-icon" id="weatherIcon" src="" alt="Weather icon">
  70.             <h2 id="cityName"></h2>
  71.             <div class="temperature" id="temperature"></div>
  72.             <div class="description" id="description"></div>
  73.             <div class="details">
  74.                 <div>Feels like: <span id="feelsLike"></span></div>
  75.                 <div>Humidity: <span id="humidity"></span></div>
  76.                 <div>Wind: <span id="wind"></span></div>
  77.                 <div>Pressure: <span id="pressure"></span></div>
  78.             </div>
  79.         </div>
  80.     </div>
  81.     <script>
  82.         document.addEventListener('DOMContentLoaded', function() {
  83.             var cityInput = document.getElementById('cityInput');
  84.             var searchButton = document.getElementById('searchButton');
  85.             var loading = document.getElementById('loading');
  86.             var error = document.getElementById('error');
  87.             var weatherContainer = document.getElementById('weatherContainer');
  88.             var weatherInfo = document.getElementById('weatherInfo');
  89.             var cityName = document.getElementById('cityName');
  90.             var temperature = document.getElementById('temperature');
  91.             var description = document.getElementById('description');
  92.             var weatherIcon = document.getElementById('weatherIcon');
  93.             var feelsLike = document.getElementById('feelsLike');
  94.             var humidity = document.getElementById('humidity');
  95.             var wind = document.getElementById('wind');
  96.             var pressure = document.getElementById('pressure');
  97.             
  98.             // API key - 在实际应用中,应该从服务器获取或使用环境变量
  99.             var apiKey = 'YOUR_API_KEY';
  100.             
  101.             searchButton.addEventListener('click', function() {
  102.                 var city = cityInput.value.trim();
  103.                 if (city) {
  104.                     getWeatherData(city);
  105.                 }
  106.             });
  107.             
  108.             cityInput.addEventListener('keypress', function(e) {
  109.                 if (e.key === 'Enter') {
  110.                     var city = cityInput.value.trim();
  111.                     if (city) {
  112.                         getWeatherData(city);
  113.                     }
  114.                 }
  115.             });
  116.             
  117.             function getWeatherData(city) {
  118.                 // 显示加载状态
  119.                 loading.style.display = 'block';
  120.                 error.style.display = 'none';
  121.                 weatherContainer.style.display = 'none';
  122.                
  123.                 var xhr = new XMLHttpRequest();
  124.                 var url = 'https://api.openweathermap.org/data/2.5/weather?q=' + encodeURIComponent(city) + '&appid=' + apiKey + '&units=metric';
  125.                
  126.                 xhr.open('GET', url, true);
  127.                
  128.                 xhr.onreadystatechange = function() {
  129.                     if (xhr.readyState === 4) {
  130.                         loading.style.display = 'none';
  131.                         
  132.                         if (xhr.status === 200) {
  133.                             var data = JSON.parse(xhr.responseText);
  134.                             displayWeatherData(data);
  135.                         } else {
  136.                             var errorMessage = 'Error fetching weather data';
  137.                             if (xhr.status === 404) {
  138.                                 errorMessage = 'City not found';
  139.                             } else if (xhr.status === 401) {
  140.                                 errorMessage = 'Invalid API key';
  141.                             }
  142.                             showError(errorMessage);
  143.                         }
  144.                     }
  145.                 };
  146.                
  147.                 xhr.onerror = function() {
  148.                     loading.style.display = 'none';
  149.                     showError('Network error');
  150.                 };
  151.                
  152.                 xhr.ontimeout = function() {
  153.                     loading.style.display = 'none';
  154.                     showError('Request timeout');
  155.                 };
  156.                
  157.                 xhr.timeout = 10000; // 10 seconds timeout
  158.                 xhr.send();
  159.             }
  160.             
  161.             function displayWeatherData(data) {
  162.                 cityName.textContent = data.name + ', ' + data.sys.country;
  163.                 temperature.textContent = Math.round(data.main.temp) + '°C';
  164.                 description.textContent = data.weather[0].description;
  165.                 feelsLike.textContent = Math.round(data.main.feels_like) + '°C';
  166.                 humidity.textContent = data.main.humidity + '%';
  167.                 wind.textContent = data.wind.speed + ' m/s';
  168.                 pressure.textContent = data.main.pressure + ' hPa';
  169.                
  170.                 // 设置天气图标
  171.                 var iconCode = data.weather[0].icon;
  172.                 weatherIcon.src = 'https://openweathermap.org/img/wn/' + iconCode + '@2x.png';
  173.                 weatherIcon.alt = data.weather[0].description;
  174.                
  175.                 // 显示天气信息
  176.                 weatherContainer.style.display = 'block';
  177.                 weatherInfo.style.display = 'block';
  178.             }
  179.             
  180.             function showError(message) {
  181.                 error.textContent = message;
  182.                 error.style.display = 'block';
  183.                 weatherContainer.style.display = 'none';
  184.             }
  185.         });
  186.     </script>
  187. </body>
  188. </html>
复制代码

这个示例展示了如何使用XMLHttpRequest创建一个简单的天气应用,包括:

1. 用户输入城市名称
2. 发送AJAX请求获取天气数据
3. 处理加载状态和错误
4. 显示天气信息

总结

XMLHttpRequest是AJAX技术的核心对象,它提供了一种在后台与服务器交换数据的方式,使得网页可以实现异步更新,无需刷新整个页面。通过本文的深入解析,我们了解了XMLHttpRequest的工作原理、API、应用场景以及最佳实践。

虽然现代浏览器提供了Fetch API作为XMLHttpRequest的替代方案,但XMLHttpRequest仍然具有其独特的优势,特别是在需要上传进度、超时控制等特定功能时。了解XMLHttpRequest的工作原理和使用方法,对于前端开发者来说仍然是非常重要的。

在实际开发中,我们应该根据项目需求和目标浏览器,选择合适的技术。无论是使用XMLHttpRequest还是Fetch API,关键是理解其工作原理,正确处理错误和边界情况,以提供良好的用户体验。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

频道订阅

频道订阅

加入社群

加入社群

联系我们|TG频道|RSS

Powered by Pixtech

© 2025 Pixtech Team.