XMLHttpRequest: handling response tutorial


In this lesson, we will learn how to receive a response from a query XMLHttpRequest. For this we need the properties

  • readyState - contains the current status of the query
  • responseText - contains the response body

Recall the script from the previous lesson:
request = getXMLHttpRequest();

request.onreadystatechange = function() {
   console.log(request.readyState);
}

request.open('GET', '/some_file.txt', true);
request.send(null)


All we need to fix is to write a code to the request-state handler that will track the state with a value of 4 and display the value of the property responseText .

request = getXMLHttpRequest();

request.onreadystatechange = function() {
   if (request.readyState == 4) {
     alert(request.responseText);
   }
}

request.open('GET', '/some_file.txt', true);
request.send(null);


On the screen we will see a modal window with the contents of the text file some_file.txt . Let's try not to turn to a simple text file, but to a PHP script. Create a file test.php , in which we write the following code:

<?php 
$a = 2 + 2 * 2;
echo $a;


Substitute the file name in the query:

request.open('GET', '/test.php', true);


Now, when executing the script, we will see 6 in the modal window; The script forms the request body with the content as a string '6' .

request = getXMLHttpRequest();

request.onreadystatechange = function() {
   if (request.readyState == 4) {
     alert(request.responseText);
   }
}
//request.open('GET', '/some_file.txt', true);
request.open('GET', '/test.php', true);
request.send(null);


In the following lessons, we will try to complicate the task and process the response body, in which we will pass the JSON string.

Замечание . Using properties status and statusText you can get information about the status of the response, for example 200 (OK), 404 (Not Found), etc.