JavaScript HTTP 请求:fetch() 和 XMLHttpRequest 实例详解
使用 JavaScript 发出 HTTP 请求可以使用内置的fetch()函数或者XMLHttpRequest对象。以下是使用这两种方法的示例代码:
使用fetch()函数:
async function makeHttpRequest(url, method, data) {
try {
const response = await fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
// 解析响应数据
const responseData = await response.json();
return responseData;
} catch (error) {
console.error('发生错误:', error);
}
}
// 使用示例
const url = 'https://example.com/api';
const method = 'POST';
const data = { name: 'John', age: 30 };
makeHttpRequest(url, method, data)
.then(response => {
console.log('响应数据:', response);
});
使用XMLHttpRequest对象:
function makeHttpRequest(url, method, data, callback) {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
const responseData = JSON.parse(xhr.responseText);
callback(responseData);
} else {
console.error('发生错误:', xhr.status);
}
}
};
xhr.send(JSON.stringify(data));
}
// 使用示例
const url = 'https://example.com/api';
const method = 'POST';
const data = { name: 'John', age: 30 };
makeHttpRequest(url, method, data, function (response) {
console.log('响应数据:', response);
});
这些示例代码可以帮助你使用 JavaScript 发出 HTTP 请求。请根据你的需求选择其中一种方法并进行适当的调整。
原文地址: http://www.cveoy.top/t/topic/IyI 著作权归作者所有。请勿转载和采集!