// 使用 XMLHttpRequest 发起 GET 请求
function getRequest(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 请求成功,调用回调函数处理响应数据
callback(xhr.responseText);
}
};
xhr.send();
}
// 示例:发起一个 GET 请求并打印响应结果
getRequest('https://jsonplaceholder.typicode.com/posts/1', function(response) {
console.log('Response:', response);
});
// 使用 Fetch API 发起 GET 请求
function fetchRequest(url) {
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // 解析 JSON 数据
})
.then(data => {
console.log('Fetched data:', data); // 处理返回的数据
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
}
// 示例:使用 Fetch API 发起请求
fetchRequest('https://jsonplaceholder.typicode.com/posts/1');
XMLHttpRequest:
xhr.open() 方法用来初始化请求,xhr.send() 发送请求。xhr.onreadystatechange 监听请求状态的变化,当 readyState 为 4(表示请求完成)且 status 为 200(表示请求成功)时,调用回调函数处理响应。Fetch API:
fetch() 返回一个 Promise,可以链式调用 .then() 和 .catch() 来处理响应和错误。response.json() 用来解析 JSON 格式的响应数据。上一篇:js websocket框架
下一篇:js foreach 退出循环
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站