// 使用 XMLHttpRequest 进行 AJAX 请求的示例
function ajaxRequest(url, callback) {
// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open('GET', url, true);
// 设置响应处理函数
xhr.onreadystatechange = function() {
// 检查请求状态是否完成且响应成功
if (xhr.readyState === 4 && xhr.status === 200) {
// 调用回调函数并传递响应数据
callback(xhr.responseText);
}
};
// 发送请求
xhr.send();
}
// 示例调用
ajaxRequest('https://api.example.com/data', function(response) {
console.log('服务器响应:', response);
});
readyState === 4 表示请求完成,status === 200 表示请求成功。如果你需要更现代的方式,可以使用 fetch API:
// 使用 fetch API 进行 AJAX 请求的示例
function fetchData(url) {
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('网络响应失败');
}
return response.json(); // 假设服务器返回 JSON 数据
})
.then(data => {
console.log('服务器响应:', data);
})
.catch(error => {
console.error('请求失败:', error);
});
}
// 示例调用
fetchData('https://api.example.com/data');
fetch 返回一个 Promise 对象,可以通过 .then() 和 .catch() 处理响应和错误。.catch() 捕获请求过程中可能发生的错误。上一篇:js ajax post
下一篇:js websocket发送消息
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站