// 使用 XMLHttpRequest 发起 GET 请求
function sendGetRequest(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 请求并处理响应
sendGetRequest('https://jsonplaceholder.typicode.com/posts/1', function(response) {
console.log('Response:', response);
});
// 使用 Fetch API 发起 GET 请求(推荐)
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // 将响应体解析为 JSON
})
.then(data => {
console.log('Data:', data); // 处理返回的数据
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
XMLHttpRequest:
xhr.open("GET", url, true) 用于设置请求方法、URL 和是否异步。xhr.onreadystatechange 用于监听请求状态的变化,当 readyState 为 4 并且 status 为 200 时,表示请求成功,可以处理响应数据。Fetch API:
fetch(url) 发起请求,返回一个 Promise。.then(response => response.json()) 将响应体解析为 JSON 格式。.catch(error => {...}) 捕获请求过程中可能发生的错误。下一篇:js arraybuffer
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站