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>

更多相关文章

  1. ThinkPHP5 微信接口对接公共类
  2. 安装编辑器与常用插件
  3. 编辑器VSCod的安装和http协议的理解
  4. 初次学习前端必备的开发工具VS Code简单安装及Http了解
  5. 第一节课:浅谈http
  6. 0628第1节课
  7. 对http协议的请求与响应过程的理解
  8. 18.)PHPWeb开发框架~Laravel中表单自动验证机制配置
  9. 16.)PHPWeb开发框架~Laravel中CSRF攻击原理讲解

随机推荐

  1. 每日前端夜话(0x05):2018年JavaScript状态
  2. 排序算法 #4 再讲插入排序
  3. 数据结构 #1 浅谈数组
  4. 再谈文件读写:判断文件的几种方法及其优劣
  5. 从一篇Blog看两个并发编程错误
  6. 每日前端夜话(0x04):2018年JavaScript状态
  7. LeetCode #27 移除元素
  8. 以B站C语言视频为基础的课后总结(一)
  9. LeetCode #26 删除排序数组中的重复项
  10. 排序算法 #5 归并排序