Ajax请求实例,与懒加载技术
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
</ul>
<img width="100%" data-src="https://img.php.cn/upload/article/000/000/003/60c034e9d3595631.jpg" alt="" />
<img width="100%" data-src="https://www.php.cn/static/images/index_yunv.jpg" alt="" />
<img width="100%" data-src="https://img.php.cn/upload/course/000/000/015/60eeb1f094ce0888.png" alt="" />
<img width="100%" data-src="https://img.php.cn/upload/course/000/000/010/60bf1859d6f23449.jpg" alt="" />
<img width="100%" data-src="https://img.php.cn/upload/course/000/000/001/5d1c6dfc9eb09885.jpg" alt="" />
<script>
// ### 2.1 xhr 请求步骤
// 1. 创建 xhr 对象: `const xhr = new XMLHttpRequest()`
// 2. 配置 xhr 参数: `xhr.open(type, url)`
// 3. 处理 xhr 响应: `xhr.onload = (...) => {...}`
// 4. 发送 xhr 请求: `xhr.send(...)`
// 问:Ajax get,post请求的区别
// 答:get请求参数会出现在地址栏,一般用户读取数据
// 答:post请求的参数会隐藏在请求头中,地址栏不会发生任何变化,相对较安全,一般用于提交数据
getData();
function getData(){
const xhr = new XMLHttpRequest();
let url = "https://api.apiopen.top/videoCategory";
xhr.open('GET',url);
xhr.responseType = 'json';
xhr.onload = function (e){
// console.log(e.currentTarget.response.result.itemList);
const ul = document.querySelector('ul');
for(let i = 0;i<e.currentTarget.response.result.itemList.length;i++){
const li = document.createElement('li');
li.textContent = e.currentTarget.response.result.itemList[i].data.description;
li.style.height = '3rem';
ul.append(li);
}
}
xhr.onerror = function (){console.log('请求错误!')};
xhr.send(null);
}
//onscroll 实现懒加载
let img = document.images;
window.onscroll = function(){
[...img].forEach(img =>{
if(img.getBoundingClientRect().top < window.innerHeight){
img.src = img.dataset.src;
}
})
}
</script>
</body>
</html>