jsbin展示
封装的ajax函数,post、get请求都可以使用
前端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")
btn.addEventListener("click", function() {
ajax({
type: "post", //可以改为get请求哦!
url: "/loadMore",
data: {
index: newsList.children.length,
needPage: 3
},
success: addNews,
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")
xhr.send(url)
}
if (opt.type === "get") {
xhr.open(opt.type, opt.url + "?" + url, true)
xhr.send()
}
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>
后端router.js
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)
})