example_of_jquery_3.html 1.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
<!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>