代码在下面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//请求所有的数据
let xhr = new XMLHttpRequest()
//设置请求
xhr.open('GET', "https://jsonplaceholder.typicode.com/todos")
//发送请求
xhr.send()
//监听请求状态
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && /^20\d$/.test(xhr.status)) {
let current = 1
let res = xhr.responseText //获取到是一个字符串
//转为数组类型 计算总数
let count = JSON.parse(res).length
//计算一个每页显示个数
const page = 9
//求出页数
const pageCount = Math.ceil(count / page) //多的内容要多一页
//先应该加载第一页的内容
cheangePage(current)
function cheangePage(currentPage) {
let xhr1 = new XMLHttpRequest
//设置请求
xhr1.open('GET', `https://jsonplaceholder.typicode.com/todos?_page=${currentPage}&_limit=9`)
//发送请求
xhr1.send()
//监听请求状态
xhr1.onreadystatechange = function() {
if (xhr1.readyState == 4 && /^20\d$/.test(xhr1.status)) {
//在监听方法中获取对应响应的内容
let res = xhr1.responseText //获取到是一个字符串
//转为数组
res = JSON.parse(res)
//渲染到页面
//创建table
if (document.querySelector('table')) {
document.querySelector('table').remove()
}
let table = document.createElement('table')
let tHead = document.createElement('tr')
let td = document.createElement('th')
td.innerText = '序号'
tHead.appendChild(td)
for (let key in res[0]) {
//创建tr和td
let td = document.createElement('th')
td.innerText = key
tHead.appendChild(td)
}
table.appendChild(tHead)
table.border = '1px'
//将table添加到body
document.body.appendChild(table)
// 拿到数据是一个数组 遍历对象数组
res.forEach((v, index) => {
//创建tr和td
let tr = document.createElement('tr')
//加序号
let firstTd = document.createElement('td')
//填充内容
firstTd.innerText = index + 1
tr.appendChild(firstTd)
for (let attr in v) {
let td = document.createElement('td')
//填充内容
td.innerText = v[attr]
tr.appendChild(td)
}
//添加到table中
table.appendChild(tr)
});
}
}
}
//生成对应的切换的按钮
let left = document.createElement('button')
left.innerText = '上一页'
document.body.appendChild(left)
for (let i = 1; i <= pageCount; i++) {
let btn = document.createElement('button')
btn.innerText = i
//切换按钮功能
btn.onclick = function() {
current = i
cheangePage(i)
isCurrent()
}
document.body.appendChild(btn)
}
let right = document.createElement('button')
right.innerText = '下一页'
document.body.appendChild(right)
isCurrent()
function isCurrent() {
if (current == 1) {
left.disabled = true
right.disabled = false
} else if (current == pageCount) {
left.disabled = false
right.disabled = true
} else {
left.disabled = false
right.disabled = false
}
}
left.onclick = function() {
current--
cheangePage(current)
isCurrent()
}
right.onclick = function() {
current++
cheangePage(current)
isCurrent()
}
}
}
</script>
</body>
</html>