JavaScript HTTP请求:XMLHttpRequest和Fetch API详细指南
JavaScript HTTP请求:XMLHttpRequest和Fetch API详细指南
想要在JavaScript中与服务器交互并动态更新网页内容?你需要掌握发送HTTP请求的技巧。本指南将带你学习两种常用的方法:XMLHttpRequest对象和更现代的fetch函数。
使用XMLHttpRequest对象
XMLHttpRequest对象是 AJAX 技术的核心,允许你发送异步HTTP请求。
function makeHttpRequest(url, method, data) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = function() {
reject(xhr.statusText);
};
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
});
}
// 示例用法
var requestUrl = 'https://api.example.com/data';
var requestData = { key: 'value' };
makeHttpRequest(requestUrl, 'GET')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.error(error);
});
代码解析:
- 创建XMLHttpRequest对象:
var xhr = new XMLHttpRequest(); - 打开请求:
xhr.open(method, url, true);其中method可以是 'GET', 'POST' 等,true表示异步请求。 - 设置回调函数:
xhr.onload处理成功响应,xhr.onerror处理请求错误。 - 发送请求:
xhr.send()发送GET请求,xhr.send(JSON.stringify(data))发送POST请求并设置请求体。
使用fetch函数
fetch 函数提供了更简洁、更现代的 API 来发送HTTP请求。
function makeHttpRequest(url, method, data) {
var options = {
method: method,
headers: {
'Content-Type': 'application/json'
}
};
if (method === 'POST') {
options.body = JSON.stringify(data);
}
return fetch(url, options)
.then(function(response) {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
});
}
// 示例用法
var requestUrl = 'https://api.example.com/data';
var requestData = { key: 'value' };
makeHttpRequest(requestUrl, 'GET')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.error(error);
});
代码解析:
- 创建请求选项:
var options = { method: method, headers: { 'Content-Type': 'application/json' } };设置请求方法、请求头等。 - 发送请求:
fetch(url, options)发送请求并返回一个Promise对象。 - 处理响应: 使用
.then()方法处理成功响应,使用.json()方法解析JSON格式的响应。
总结
XMLHttpRequest 和 fetch 都可以用来发送 JavaScript HTTP 请求。fetch API 语法更简洁,更易于使用,建议优先选择。
记住: 以上代码片段只是基本示例,实际应用中,你可能需要根据具体的需求进行自定义和错误处理,例如设置请求头、处理不同类型的响应数据等。
原文地址: https://www.cveoy.top/t/topic/RyX 著作权归作者所有。请勿转载和采集!