<script type="text/javascript">
class Book {
// Конструктор
constructor(objBook) {
this.name = objBook.name;
this.isbn = objBook.isbn;
this.authors = "";
for (let i = 0; i < objBook.authors.length; i++) {
this.authors += objBook.authors[i] + " ";
}
this.numberOfPages = objBook.numberOfPages;
}
// Функция создает строку таблицы
createTableRow() {
let nodeRow = document.createElement('TR');
let node = document.createElement('TD');
let anchor = document.createElement('a');
anchor.href = "#";
anchor.innerText = this.name;
node.appendChild(anchor)
nodeRow.appendChild(node);
node = document.createElement('TD');
node.innerText = this.authors;
nodeRow.appendChild(node);
node = document.createElement('TD');
node.innerText = this.numberOfPages;
nodeRow.appendChild(node);
node = document.createElement('TD');
node.innerText = this.isbn;
nodeRow.appendChild(node);
// Добавляем новую строку в таблицу
let table = document.getElementById('maintable');
table.appendChild(nodeRow);
}
// Преобразование объекта в строку.
toString() {
return "Book name: \"" + this.name + "\" - \"" + this.authors + "\"";
}
}
// Запрашиваем список книг
function getBooks() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://anapioficeandfire.com/api/books", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let books = [];
let rspns = JSON.parse(xhr.response);
for (var i = 0; i < rspns.length; i++) {
books[i] = new Book(rspns[i]);
books[i].createTableRow();
console.log(books[i].toString());
}
//console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null); // При POST включается содержание запроса
}
<h1>Список книг Game of Thrones</h1>
<p>
<input type="button" value="Получить список" onclick="getBooks()">
</p>
<table id="maintable">
<tr>
<th value="Получить список" onclick="getBooks()">Название</th>
<th>Автор</th>
<th>Количество страниц</th>
<th>ISBN</th>
</tr>
</table>