JavaScript HTTP 请求: 使用 XMLHttpRequest 和 Fetch
使用 JavaScript 发出 HTTP 请求可以通过内置的'XMLHttpRequest' 对象或者现代浏览器中的'fetch' 函数来实现。以下是使用这两种方法中的任意一种的示例代码:
使用 XMLHttpRequest:
function sendHttpRequest(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);
});
}
// 示例用法:
var url = 'https://api.example.com/data';
var method = 'GET';
var data = null;
sendHttpRequest(url, method, data)
.then(function(response) {
console.log('请求成功:', response);
})
.catch(function(error) {
console.error('请求失败:', error);
});
使用 fetch 函数:
function sendHttpRequest(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.status);
}
return response.json();
});
}
// 示例用法:
var url = 'https://api.example.com/data';
var method = 'GET';
var data = null;
sendHttpRequest(url, method, data)
.then(function(response) {
console.log('请求成功:', response);
})
.catch(function(error) {
console.error('请求失败:', error);
});
请注意,编写实际应用程序时,您需要根据您的特定要求和后端 API 的要求进行适当的更改和设置。
原文地址: https://www.cveoy.top/t/topic/bOHO 著作权归作者所有。请勿转载和采集!