JavaScript HTTP 请求: XMLHttpRequest 和 fetch 函数
使用 JavaScript 发出 HTTP 请求的常见方法是使用内置的浏览器 API——XMLHttpRequest 对象或 fetch 函数。以下是使用这两种方法的示例:
使用 XMLHttpRequest 对象:
function sendHttpRequest(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.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(JSON.stringify(data));
});
}
使用 fetch 函数:
function sendHttpRequest(url, method, data) {
return fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(function(response) {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
});
}
使用示例:
var url = 'https://api.example.com/endpoint';
var method = 'POST';
var data = { key: 'value' };
sendHttpRequest(url, method, data)
.then(function(response) {
console.log('请求成功', response);
})
.catch(function(error) {
console.error('请求失败', error);
});
请注意,这只是一种使用 JavaScript 发出 HTTP 请求的方法,具体的实现可能因您的需求和环境而有所不同。
原文地址: https://www.cveoy.top/t/topic/bKEL 著作权归作者所有。请勿转载和采集!