<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> </head> <body> <button onclick="loadPhones()" id="button">Загрузить phones.json!</button> <ul id="list"></ul> <script> function loadPhones() { var xhr = new XMLHttpRequest(); xhr.open('GET', 'phones.json', true); xhr.onreadystatechange = function () { if (xhr.readyState != 4) return; button.innerHTML = 'Готово!'; if (xhr.status != 200) { // обработать ошибку alert(xhr.status + ': ' + xhr.statusText); } else { // вывести результат try { var phones = JSON.parse(xhr.responseText); } catch (e) { alert("Некорректный ответ " + e.message); } showPhones(phones); } }; xhr.send(); button.innerHTML = 'Загружаю...'; button.disabled = true; } function showPhones(phones) { phones.forEach(function (phone) { var li = list.appendChild(document.createElement('li')); li.innerHTML = phone.name; }); } </script> </body> </html> 

Hello

He began to study Ajax and immediately misunderstood. Can someone explain in steps what we are doing here?

Closed due to the fact that off-topic participants Alexey Shimansky , Dmitriy Simushev , cheops , PashaPash 14 May '16 at 8:33 .

  • Most likely, this question does not correspond to the subject of Stack Overflow in Russian, according to the rules described in the certificate .
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • where is it from? why this particular code? break in the lines, comment out, delete, add, rewrite, restart - what do you want in the final result ?! - titov_andrei
  • Well, study further, apparently not enough studied. - Jean-Claude
  • @titov_andrei found on learn.javascript - Nikita Shchypylov
  • @ Jean-Claude, of course, not enough) I will - Nikita Shchypylov

2 answers 2

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; 
     <button onclick="loadPhones()" id="button">Загрузить phones.json!</button> 

    Pressing the button calls the loadPhones function.

     var xhr = new XMLHttpRequest(); xhr.open('GET', 'phones.json', true); xhr.onreadystatechange = function () { ... } 

    We form an asynchronous request to the server (the browser does not wait for the request to be executed) to receive the phones.json file and connect the handler for the request status change event. This anonymous function will be called automatically when the request states change.

     xhr.send(); 

    Perform a request to the server, while the function send() does not stop the execution of the script.

     button.innerHTML = 'Загружаю...'; button.disabled = true; 

    Change the button text and disable it.

    Now back to the request status handler.

     if (xhr.readyState != 4) return; 

    Check the readyState property. We are interested in the state 4 - DONE . If we receive it then the request has completed its work. In general, this property can take the following values:

    • 0 - UNSENT
    • 1 - OPENED
    • 2 - HEADERS_RECEIVED
    • 3 - LOADING
    • 4 - DONE

    Their purpose can be found in the documentation, for example here or here .

     if (xhr.status != 200) { // обработать ошибку alert(xhr.status + ': ' + xhr.statusText); } else { 

    This is a server response code verification. If the code! = 200, then we give an error message.

     var phones = JSON.parse(xhr.responseText); showPhones(phones); 

    We parse the response, convert it into an array of objects, while parsing the JSON string we enclose it in an exception handler. Well, print the result of the query.

     phones.forEach(function (phone) { var li = list.appendChild(document.createElement('li')); li.innerHTML = phone.name; }); 

    This is actually the final visualization of the query result. Here we create for each element of the array of phones an element html- li markup with the name of the phone and insert it as a child of the list <ul id="list"></ul> .

    • Thank you very much! Be sure to review everything - Nikita Shchypylov