The button button is displayed on the page:
<button onclick="loadPhones()" id="button">Загрузить phones.json!</button>
By clicking on it, the onclick event is triggered. The event initiates a call to the loadPhones javascript function. Next, look what the loadPhones function loadPhones .
In the function, create an instance of the XMLHttpRequest object in the xhr variable. This is the object that allows you to perform ajax requests:
var xhr = new XMLHttpRequest();
We indicate to the object that we will request the url "phones.json" by the http method GET.
xhr.open('GET', 'phones.json', true);
In onreadystatechange specify the actions that will be performed each time the xhr (readyState) object changes its readiness state.
xhr.onreadystatechange = function () {
In total there are 5 states of the XMLHttpRequest object from 0 to 4:
0: request not initialized
1: connected to server
2: Request received
3: request processing
4: the request is completed and the response is ready
This code indicates that if the request is not completed yet, then we do nothing - we do return (that is, return from a function).
if (xhr.readyState != 4) return;
If the server responded with http-code! = 200, then js alert flies (as such error handling):
if (xhr.status != 200) { // обработать ошибку alert(xhr.status + ': ' + xhr.statusText);
The following code is executed if only status == 200 and state == 4. It is expected that the server will return a response in json format.
// вывести результат try { var phones = JSON.parse(xhr.responseText); } catch (e) { alert("Некорректный ответ " + e.message); }
If suddenly the server returned an answer not in json or we could not parse json, an exception will be thrown, which is immediately caught in the catch and an alert will be displayed on the screen.
If everything went ok, then the showPhones function will be executed:
showPhones(phones);
Which each phone inserts into the new <li> in the <ul> block:
phones.forEach(function (phone) { var li = list.appendChild(document.createElement('li')); li.innerHTML = phone.name; });
Directly sending an ajax request:
xhr.send();
Here, I think, it is clear that when you click on a button, the name of the button is replaced and repeated presses are blocked:
button.innerHTML = 'Загружаю...'; button.disabled = true;
Where you have:
// вывести результат
In an amicable way, everything should be returned back:
button.innerHTML = 'Загружено!'; button.disabled = false;