Ajax(Asynchronous JavaScript and XML)是一种用于创建快速动态网页的技术。它通过在不重新加载整个页面的情况下,与服务器进行异步通信来更新部分页面内容。
主要作用是实现页面的局部刷新
,在不刷新整个页面的情况下,动态地加载数据,提高用户体验,减少页面加载时间。
使用原生JS的XMLHTTPRequest实现Ajax:
// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open('GET', 'https://api.example.com/data', true);
// 发送请求
xhr.send();
// 监听状态改变事件
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// 请求成功
var response = xhr.responseText;
console.log(response);
} else {
// 请求失败
console.log('请求失败:' + xhr.status);
}
}
};