- 有时候网络延时,用户多次点击按钮发送请求,后端接收到多个重复的请求,浪费流量。
前端html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
ul,
li {
list-style: none;
padding: 0;
margin: 0;
}
#news>li {
width: 600px;
border: 1px solid #000080;
border-radius: 5px;
font-size: 1.25rem;
margin: 0 auto;
text-align: center;
padding: 5px;
margin-top: 10px;
}
.btn {
width: 200px;
display: block;
margin: 0 auto;
margin-top: 20px;
font-size: 1.5rem;
padding: 10px;
background: #AFEEEE;
}
</style>
</head>
<body>
<ul id="news">
<li>新闻1</li>
<li>新闻2</li>
<li>新闻3</li>
<li>新闻4</li>
<li>新闻5</li>
</ul>
<button id="more" class="btn">加载更多</button>
</body>
<script>
var btn = $("#more");
var newsList = $("#news");
var dataLock = true; // 数据锁初始是打开的
btn.addEventListener("click", function() {
if (!dataLock) {
return
} // 查看数据锁是否关闭,如果关闭就退出函数
dataLock = false;
ajax({
type: "get", //可以改为post请求哦!
url: "/loadMore",
data: {
index: newsList.children.length,
needPage: 3
},
success: function (callback){
addNews(callback);
dataLock = true; // 后端发回数据后,打开数据锁
},
error: function() {
console.log("出错了")
}
})
})
function addNews(arr) {
var frag = document.createDocumentFragment();
for (var i = 0; i < arr.length; i++) {
var list = document.createElement("li");
list.innerText = arr[i];
frag.appendChild(list);
}
news.appendChild(frag)
}
function ajax(opt) {
var xhr = new XMLHttpRequest();
// /loadMore?index=5&needPage=3&
var url = "";
for (var key in opt.data) {
url += key + "=" + opt.data[key] + "&";
}
console.log("url:", url)
if (opt.type === "post") {
xhr.open(opt.type, opt.url, true)
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
setTimeout(function(){ // 模拟网络延时,2秒后发送请求
xhr.send(url)
}, 2000)
}
if (opt.type === "get") {
xhr.open(opt.type, opt.url + "?" + url, true)
setTimeout(function() { // 模拟网络延时,2秒后发送请求
xhr.send()
}, 2000)
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 304) {
var result = JSON.parse(xhr.responseText)
console.log(result)
opt.success(result)
} else {
opt.error()
}
}
}
}
function $(str) {
return document.querySelector(str);
}
</script>
</html>
app.get("/loadMore", function(req, res) {
var idx = req.query.index;
var ndpg = req.query.needPage;
var news = [];
for (var i = 0; i < ndpg; i++) {
news.push("新闻get" + (parseInt(idx) + i + 1))
}
res.send(news)
})
app.post("/loadMore", function(req, res) {
var idx = req.body.index;
var ndpg = req.body.needPage;
var news = [];
for (var i = 0; i < ndpg; i++) {
news.push("新闻post" + (parseInt(idx) + i + 1))
}
res.send(news)
// setTimeout(function(){
// res.send(news)
// }, 1000)
})
网友评论