/
index.html
119 lines (107 loc) · 3.11 KB
/
index.html
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ajaxExample</title>
<style>
*{
padding: 0;
margin: 0;
list-style: none;
text-align: center;
}
li{
margin: 10px 10px;
font-size: 30px;
border: 1px solid #999;
cursor: pointer;
}
#load-more{
margin-top: 10px;
padding: 5px 10px;
border-radius: 4px;
color: white;
background-color: #009688;
text-decoration: none;
}
#load-more:hover{
opacity: 0.8;
}
</style>
</head>
<body>
<div class="ct">
<ul>
<li>news 1</li>
<li>news 2</li>
</ul>
<ul id="addInThis"></ul>
<a href="#" id="load-more">load more</a>
</div>
<script>
function $(id) {
return document.querySelector(id);
}
var pageIndex = 3;
var isDataArrive = true;
$('#load-more').addEventListener('click', function(e){
e.preventDefault();
if(!isDataArrive){
return;
}
loadData(function(news){
renderPage(news);
pageIndex = pageIndex + 5;
isDataArrive = true;
});
isDataArrive = false;
});
function loadData(callback) {
ajax({
type: 'get',
url: '/loadMore',
data: {
index: pageIndex,
length: 5
},
onSuccess: callback,
onError: function () {
console.log('error');
}
})
}
function renderPage(news){
var fragment = document.createDocumentFragment();
for(var i = 0; i < news.length; i++){
var node = document.createElement('li');
node.innerText = news[i];
fragment.appendChild(node);
}
$('#addInThis').appendChild(fragment);
}
function ajax(options){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if( xhr.status === 200 || xhr.status == 304){
var results = JSON.parse(xhr.responseText);
options.onSuccess(results);
}else{
options.onError();
}
}
}
var query = '?';
for(key in options.data){
query += key + '=' + options.data[key] + '&';
}
query = query.substr(0, query.length-1);
xhr.open(options.type, options.url + query, true);
xhr.send()
}
</script>
</body>
</html>