example_of_jquery_3.html 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Ajax请求</title>
  6. </head>
  7. <body>
  8. <button id="load">加载更多</button>
  9. <div id="photos"></div>
  10. <script>
  11. (() => {
  12. const photos = document.querySelector('#photos')
  13. const loadBtn = document.querySelector('#load')
  14. const url = 'http://api.tianapi.com/meinv/?key=772a81a51ae5c780251b1f98ea431b84&page='
  15. var page = 0
  16. loadBtn.addEventListener('click', (evt) => {
  17. page += 1
  18. // 创建异步请求对象
  19. let xhr = new XMLHttpRequest()
  20. // open方法的第一个参数是请求类型, 第二个参数是请求的URL, 第三个参数必须设置为true(异步请求)
  21. xhr.open('get', url + page, true)
  22. // 绑定事件回调函数,在收到服务器返回的数据后要对页面进行局部刷新
  23. xhr.addEventListener('readystatechange', () => {
  24. if (xhr.readyState == 4 && xhr.status == 200) {
  25. // 将返回的JSON字符串解析成JavaScript的对象
  26. let json = JSON.parse(xhr.responseText)
  27. json.newslist.forEach((mm) => {
  28. let img = document.createElement('img')
  29. img.src = mm.picUrl
  30. img.width = '300'
  31. photos.insertBefore(img, photos.firstElementChild)
  32. })
  33. }
  34. })
  35. // 发送异步请求
  36. xhr.send()
  37. })
  38. })()
  39. </script>
  40. </body>
  41. </html>