JavaScript发送HTTP请求完全指南:XMLHttpRequest和Fetch API实战
JavaScript发送HTTP请求完全指南:XMLHttpRequest和Fetch API实战
在现代网页开发中,使用JavaScript发送HTTP请求获取或发送数据至服务器是至关重要的。本文将介绍两种常用的方法:传统的XMLHttpRequest对象和现代的fetch API,并提供详细的代码示例。
1. 使用XMLHttpRequest对象
XMLHttpRequest对象是AJAX技术的核心,允许异步地与服务器交互,而无需刷新整个页面。
function makeHttpRequest(url, method, data) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(xhr.statusText);
}
}
};
xhr.onerror = function() {
reject(xhr.statusText);
};
xhr.send(data);
});
}
// 示例用法
makeHttpRequest('https://api.example.com/data', 'GET')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log('请求失败:', error);
});
这段代码定义了一个名为makeHttpRequest的函数,它接受URL、请求方法(GET、POST等)和可选的数据作为参数。该函数返回一个Promise对象,用于处理异步操作的结果。
2. 使用fetch API
fetch API是近年来兴起的一种更简洁、更现代的发送HTTP请求的方式。它返回一个Promise对象,使处理响应数据更加直观。
function makeHttpRequest(url, method, data) {
var options = {
method: method,
headers: {
'Content-Type': 'application/json'
}
};
if (data) {
options.body = JSON.stringify(data);
}
return fetch(url, options)
.then(function(response) {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.catch(function(error) {
console.log('请求失败:', error);
});
}
// 示例用法
makeHttpRequest('https://api.example.com/data', 'GET')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log('请求失败:', error);
});
这段代码展示了使用fetch API发送GET请求的示例。options对象可以设置请求头、请求体等参数。response.json()方法用于将响应数据解析为JSON格式。
总结
无论是使用XMLHttpRequest还是fetch API,都可以轻松地使用JavaScript发送HTTP请求。fetch API以其简洁易用的语法和Promise-based的异步处理方式,正逐渐成为现代Web开发的首选方案。
原文地址: https://www.cveoy.top/t/topic/bxsP 著作权归作者所有。请勿转载和采集!