Blogger Information
Blog 34
fans 0
comment 0
visits 20303
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Ajax请求实例,与懒加载技术
小庄
Original
513 people have browsed it

Ajax请求实例,与懒加载技术


  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <ul>
  11. </ul>
  12. <img width="100%" data-src="https://img.php.cn/upload/article/000/000/003/60c034e9d3595631.jpg" alt="" />
  13. <img width="100%" data-src="https://www.php.cn/static/images/index_yunv.jpg" alt="" />
  14. <img width="100%" data-src="https://img.php.cn/upload/course/000/000/015/60eeb1f094ce0888.png" alt="" />
  15. <img width="100%" data-src="https://img.php.cn/upload/course/000/000/010/60bf1859d6f23449.jpg" alt="" />
  16. <img width="100%" data-src="https://img.php.cn/upload/course/000/000/001/5d1c6dfc9eb09885.jpg" alt="" />
  17. <script>
  18. // ### 2.1 xhr 请求步骤
  19. // 1. 创建 xhr 对象: `const xhr = new XMLHttpRequest()`
  20. // 2. 配置 xhr 参数: `xhr.open(type, url)`
  21. // 3. 处理 xhr 响应: `xhr.onload = (...) => {...}`
  22. // 4. 发送 xhr 请求: `xhr.send(...)`
  23. // 问:Ajax get,post请求的区别
  24. // 答:get请求参数会出现在地址栏,一般用户读取数据
  25. // 答:post请求的参数会隐藏在请求头中,地址栏不会发生任何变化,相对较安全,一般用于提交数据
  26. getData();
  27. function getData(){
  28. const xhr = new XMLHttpRequest();
  29. let url = "https://api.apiopen.top/videoCategory";
  30. xhr.open('GET',url);
  31. xhr.responseType = 'json';
  32. xhr.onload = function (e){
  33. // console.log(e.currentTarget.response.result.itemList);
  34. const ul = document.querySelector('ul');
  35. for(let i = 0;i<e.currentTarget.response.result.itemList.length;i++){
  36. const li = document.createElement('li');
  37. li.textContent = e.currentTarget.response.result.itemList[i].data.description;
  38. li.style.height = '3rem';
  39. ul.append(li);
  40. }
  41. }
  42. xhr.onerror = function (){console.log('请求错误!')};
  43. xhr.send(null);
  44. }
  45. //onscroll 实现懒加载
  46. let img = document.images;
  47. window.onscroll = function(){
  48. [...img].forEach(img =>{
  49. if(img.getBoundingClientRect().top < window.innerHeight){
  50. img.src = img.dataset.src;
  51. }
  52. })
  53. }
  54. </script>
  55. </body>
  56. </html>
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!