Skip to content

Instantly share code, notes, and snippets.

@13hoop
Last active March 11, 2017 12:57
Show Gist options
  • Select an option

  • Save 13hoop/f45620e3a2eb15807384da412795fb99 to your computer and use it in GitHub Desktop.

Select an option

Save 13hoop/f45620e3a2eb15807384da412795fb99 to your computer and use it in GitHub Desktop.
loadMore
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>server-mock使用说明</title>
<style>
body {
background: #eee;
}
.container{
width: 900px;
margin: 0 auto;
background: white;
text-align: center;
}
button {
width: 100px;
background-color: seagreen;
}
ul {
text-align: left;
}
li {
padding: 10px 10px;
margin:10px 10px;
background: lightblue;
border: 1px solid maroon;
border-radius: 5px;
}
li:hover {
background: yellowgreen;
}
</style>
</head>
<body>
<div class="container">
加载更多demo
<br>
<ul>
</ul>
<button>loadMore</button>
</div>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
var btn = $('button')[0]
var ul = $('ul')[0]
var ajaxFuc = function(opts) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304)) {
var result = JSON.parse(xhr.responseText)
console.log("。。。到服务器了。。。")
console.log(result)
opts.success(result)
}else {
console.log("错误;")
// opts.error(xhr.status + ": " + xhr.statusText)
}
}
// console.log(opts.url)
// xhr.open('get', opts.url, true)
// xhr.send()
switch (opts.metherd.toLowerCase()) {
case 'get':
xhr.open('get', opts.url, true)
xhr.send(null)
break;
case 'post':
xhr.open('post', opts.url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.send(data)
break;
default:
return
}
}
var flag = false
var index = 0
btn.addEventListener('click', function(){
this.innerText = 'loading ...'
if(flag) { return }
ajaxFuc({
metherd: 'get',
url: '/loadMore?index=' + index,
success: function(result) {
btn.innerText = 'loadMore'
index += 5
console.log(result)
var fregment = document.createDocumentFragment()
for(var i=0; i < 5; i++) {
var node = document.createElement('li')
node.innerText = result[i]
fregment.appendChild(node)
}
ul.appendChild(fregment)
},
error: function(msg) {
// console.log(msg)
btn.innerText = 'loadMore'
}
})
})
</script>
</body>
</html>
/**
* 发送 GET 请求, 有参数
* GET /loadMore?index=0
* 默认一次性返回5个数据
*/
app.get('/loadMore', function(req, res) {
var data = []
var index = req.query.index
for(var i=0; i < 5; i++) {
data.push(Number(index) + i)
}
res.send(data)
});
@13hoop
Copy link
Author

13hoop commented Mar 10, 2017

loadMore:
ajax + jQuery

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment