| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Ajax请求</title>
- </head>
- <body>
- <button id="load">加载更多</button>
- <div id="photos"></div>
- <script>
- (() => {
- const photos = document.querySelector('#photos')
- const loadBtn = document.querySelector('#load')
- const url = 'http://api.tianapi.com/meinv/?key=772a81a51ae5c780251b1f98ea431b84&page='
- var page = 0
- loadBtn.addEventListener('click', (evt) => {
- page += 1
- // 创建异步请求对象
- let xhr = new XMLHttpRequest()
- // open方法的第一个参数是请求类型, 第二个参数是请求的URL, 第三个参数必须设置为true(异步请求)
- xhr.open('get', url + page, true)
- // 绑定事件回调函数,在收到服务器返回的数据后要对页面进行局部刷新
- xhr.addEventListener('readystatechange', () => {
- if (xhr.readyState == 4 && xhr.status == 200) {
- // 将返回的JSON字符串解析成JavaScript的对象
- let json = JSON.parse(xhr.responseText)
- json.newslist.forEach((mm) => {
- let img = document.createElement('img')
- img.src = mm.picUrl
- img.width = '300'
- photos.insertBefore(img, photos.firstElementChild)
- })
- }
- })
- // 发送异步请求
- xhr.send()
- })
- })()
- </script>
- </body>
- </html>
|