-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
104 lines (76 loc) · 2.7 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
<!DOCTYPE html>
<html>
<head>
<title>play with ajax</title>
</head>
<body>
<div id="images">
Loading ..
</div>
<button onclick="getImages()">Get images</button>
<style type="text/css">
#images img {
height: 50px;
margin: 3px;
}
</style>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script type="text/javascript">
var get = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState != xhr.DONE) return;
var status = xhr.status;
var headers = xhr.getAllResponseHeaders();
var text = xhr.responseText;
callback(status, headers, text);
}
xhr.send();
}
var appendImage = function (url) {
var imgEl = document.createElement('img');
// <img />
imgEl.src = url;
// <img src="{url}" />
imgEl.onerror = function () {
imgEl.style.display = 'none';
// when image loading failed
// @todo hide image
//alert(1);
}
document.getElementById('images').appendChild(imgEl);
}
// getImages({limit: 5})
// getImages({})
// getImages() -- by default should take 100 images
// getImages({category: "cats"})
// getImages()
// "S"OLID, S -> Single Responsibility
var getImages = function (params) {
//
// var url = 'https://www.reddit.com/r/pics.json';
var category = 'pics';
var limit = 100;
if (params && params.category) {
category = params.category;
}
var url = 'https://www.reddit.com/r/pics/search.json?q=' + category;
if (params && params.limit) {
limit = params.limit;
}
url = url + '&limit=' + limit ;
// @todo: use here params.limit
// @todo: category == "pics"
get(url, function (status, headers, body) {
var response = JSON.parse(body);
_.each(response.data.children, function (child) {
var url = child.data.url;
appendImage(url);
console.log('ITEM!', child.data.url);
});
});
}
</script>
</body>
</html>