generated from Code-Institute-Org/gitpod-full-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
91 lines (76 loc) · 2.43 KB
/
main.js
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
// const baseURL = "https://ci-swapi.herokuapp.com/api/";
function getData(url, cb) {
let xhr = new XMLHttpRequest();
// let data;
/* function setData(jsonData) {
data = jsonData;
console.log(data);
} */
xhr.onreadystatechange = function () {
// console.log(this.readyState);
if (this.readyState == 4 && this.status == 200) {
/* document.getElementById("data").innerHTML = this.responseText;
console.log(typeof (JSON.parse(this.responseText)));
console.log(JSON.parse(this.responseText));
data = this.responseText;
console.log(data);
setData(JSON.parse(this.responseText));
data = JSON.parse(this.responseText); */
cb(JSON.parse(this.responseText));
}
};
xhr.open("GET", url);
xhr.send();
}
function getTableHeaders(obj) {
let tableHeaders = [];
Object.keys(obj).forEach(function (key) {
tableHeaders.push(`<td>${key}</td>`);
});
return `<tr>${tableHeaders}</tr>`;
}
function generatePaginationButtons(next, prev) {
if (next && prev) {
return `<button onclick="writeToDocument('${prev}')">Previous</button>
<button onclick="writeToDocument('${next}')">Next</button>`;
} else if (next && !prev) {
return `<button onclick="writeToDocument('${next}')">Next</button>`;
} else if (!next && prev) {
return `<button onclick="writeToDocument('${prev}')">Previous</button>`;
}
}
function writeToDocument(url) {
let tableRows = [];
let el = document.getElementById("data");
// el.innerHTML = "";
getData(url, function (data) {
let pagination = "";
if (data.next || data.previous) {
pagination = generatePaginationButtons(data.next, data.previous);
}
// console.dir(data);
data = data.results;
let tableHeaders = getTableHeaders(data[0]);
data.forEach(function (item) {
// el.innerHTML += "<p>" + item.name + "</p>";
let dataRow = [];
Object.keys(item).forEach(function (key) {
let rowData = item[key].toString();
let truncatedData = rowData.substring(0, 15);
dataRow.push(`<td>${truncatedData}</td>`);
});
tableRows.push(`<tr>${dataRow}</tr>`);
});
el.innerHTML = `<table>${tableHeaders}${tableRows}</table>${pagination}`.replace(/,/g, "");
});
}
/* setTimeout(function () {
console.log(data);
}, 500);
function printDataToConsole(data) {
console.log(data);
}
getData(printDataToConsole);
getData(function (data) {
console.log(data);
}); */