JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API
使用 JavaScript 发出 HTTP 请求可以使用内置的 XMLHttpRequest 对象或者更现代化的 Fetch API。以下是使用两种方法的示例:
使用 XMLHttpRequest 对象:
function makeHttpRequest(url, method, data) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = function() {
reject(xhr.statusText);
};
xhr.send(JSON.stringify(data));
});
}
// 示例用法:
var requestUrl = 'https://api.example.com/data';
var requestData = { key: 'value' };
makeHttpRequest(requestUrl, 'POST', requestData)
.then(function(response) {
console.log('请求成功:', response);
})
.catch(function(error) {
console.error('请求失败:', error);
});
使用 Fetch API:
function makeHttpRequest(url, method, data) {
var options = {
method: method,
headers: {
'Content-Type': 'application/json'
},
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, 'POST', requestData)
.then(function(response) {
console.log('请求成功:', response);
})
.catch(function(error) {
console.error('请求失败:', error);
});
这些示例展示了如何使用 JavaScript 发出 HTTP 请求并处理响应。您可以根据需要修改代码,例如更改请求的 URL、请求方法或请求的数据。
原文地址: https://www.cveoy.top/t/topic/RA7 著作权归作者所有。请勿转载和采集!