Answer the question
In order to leave comments, you need to log in
How to refactor API (JS) using objects?
I wrote a code that interacts with the Star Wars API (SWAPI) - it takes a value from the user from the input and looks for matches on the site. With a select, you can select a specific type of search - ship, character or planet and limit the search. How to do refactoring - write a function that will accept select.value as an argument, and depending on the value, substitute the necessary markup? How can I make the data for this markup be substituted from the dateToInsert object?
let searchButton = document.querySelector('.searchButton');
let search = document.querySelector('.search');
let searchResult = document.querySelector('.search_result');
let name = document.querySelector('.name');
let height = document.querySelector('.height');
let mass = document.querySelector('.mass');
let birth_year = document.querySelector('.birth_year');
let films_count = document.querySelector('.films_count');
let select = document.querySelector('.select');
let div1 = document.querySelector('.div1');
let div2 = document.querySelector('.div2');
let div3 = document.querySelector('.div3');
let div4 = document.querySelector('.div4');
let div5 = document.querySelector('.div5');
let response;
window.onload = function () {
select = document.querySelector('.select');
let api = "https://swapi.dev/api/";
let url = api + select.value + "/?search=";
url += search.value;
getRevenueByID = async (arr) => {
let request = await fetch(url);
if (request.ok) { // если HTTP-статус в диапазоне 200-299
response = await request.json();
} else {
alert("Ошибка HTTP: " + response.status);
}
if (response.count == 0) {
alert("К сожалению, данные не получены по запросу: " + url);
return;
}
// alert("Найдено персонажей:" + response.count);
for (let i = 0; i < response.results.length; i++) {
let l1 = document.createElement('li');
l1.setAttribute('name', i)
l1.textContent = response.results[i].name;
searchResult.appendChild(l1);
}
};
};
searchButton.addEventListener('click', function () {
while (searchResult.firstChild) {
searchResult.removeChild(searchResult.firstChild);
}
if (search.value != '') {
onload();
getRevenueByID();
search.value = '';
} else {
alert('Пустая строка');
}
});
searchResult.addEventListener('click', function (ev) {
let target = event.target;
if (target.className != 'search_result') {
let index = target.getAttribute('name');
if (select.value == 'people') {
div2.innerHTML = 'Рост:<span class="height"></span>';
div3.innerHTML = 'Вес:<span class="mass"></span>';
div4.innerHTML = 'Год рождения:<span class="birth_year"></span>';
div5.innerHTML = 'В скольки фильмах появлялся:<span class="films_count"></span>';
name = document.querySelector('.name');
height = document.querySelector('.height');
mass = document.querySelector('.mass');
birth_year = document.querySelector('.birth_year');
films_count = document.querySelector('.films_count');
name.textContent = response.results[index].name;
height.textContent = response.results[index].height;
mass.textContent = response.results[index].mass;
birth_year.textContent = response.results[index].birth_year;
films_count.textContent = response.results[index].films.length;
}
if (select.value == 'planets') {
div2.innerHTML = 'День(часов):<span class="height"></span>';
div3.innerHTML = 'Год(дней):<span class="mass"></span>';
div4.innerHTML = 'Ландшафт:<span class="birth_year"></span>';
div5.innerHTML = 'Популяция:<span class="films_count"></span>';
name = document.querySelector('.name');
height = document.querySelector('.height');
mass = document.querySelector('.mass');
birth_year = document.querySelector('.birth_year');
films_count = document.querySelector('.films_count');
name.textContent = response.results[index].name;
height.textContent = response.results[index].rotation_period;
mass.textContent = response.results[index].orbital_period;
birth_year.textContent = response.results[index].terrain;
films_count.textContent = response.results[index].population;
}
if (select.value == 'starships') {
div2.innerHTML = 'Модель:<span class="height"></span>';
div3.innerHTML = 'Стоимость в кредитах:<span class="mass"></span>';
div4.innerHTML = 'Пассажиров:<span class="birth_year"></span>';
div5.innerHTML = 'Длинна:<span class="films_count"></span>';
name = document.querySelector('.name');
height = document.querySelector('.height');
mass = document.querySelector('.mass');
birth_year = document.querySelector('.birth_year');
films_count = document.querySelector('.films_count');
name.textContent = response.results[index].name;
height.textContent = response.results[index].model;
mass.textContent = response.results[index].cost_in_credits;
birth_year.textContent = response.results[index].passengers;
films_count.textContent = response.results[index].length;
}
}
});
//данные для разметки
var dateToInsert = {
people: {
height: "рост",
mass: "вес",
birth_year: "год рождения",
films_count: "в каком количестве фильмов появлялся",
},
starships: {
model: "модель",
cost_in_credits: "стоимость в кредитах",
passengers: "пассажиров",
length: "длина",
},
planets: {
rotation_period: "день (часов)",
orbital_period: "год (дней)",
terrain: "ландшафт",
population: "население",
}
}
// необходимая функция
function toggleMarking () {
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question