As far as I understand, you are in the wrong place doing the processing of the result obtained. Here is your example, only slightly rewritten, addEventListener used instead of onreadystatechange . Actually, inside this function and place the processing of your result in the jsonResponse variable that jsonResponse declared inside the method:
var xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.open("GET", "https://js.dump.academy/code-and-magick/data", true); xhr.onreadystatechange = function() { if (xhr.readyState != 4) return; if (xhr.status != 200) { console.log(xhr.status + ": " + xhr.statusText); } else { var jsonResponse = xhr.response; // вот тут должен быть ваш JSON в ответе // далее работа с переменной jsonResponse в которой лежит ответ (данные из JSON) } }; xhr.send();
In open , the third argument is true (or if there is no third argument) and the request is executed asynchronously. This means that after calling xhr.send() code does not “hang”, but continues to be executed, and the result of the response to the request comes through the onreadystatechange event. The readystatechange event occurs several times in the process of sending and receiving a response, the readyState state is 4 (the request is completed).
Small note : In IE8 and IE9, XMLHttpRequest support is limited. IE9 caches all responses by default. In IE11, xhr.responseType = 'json' does not work, because it is not supported in it. If you do not specify the request type as JSON, then you need to search in responseText , and not in response your result. This applies to configuration using the application/json or when there is no responseType indication.
In this case, the server should return JSON as text, which the browser turns into an object by calling JSON.parse(xhr.responseText) (in the case of JSON.parse(xhr.response) ) and we work with the response as an object.
Also, I advise you to read about the xhr.open(method, URL, async, user, password) parameters xhr.open(method, URL, async, user, password) - pay attention to the third parameter async - which indicates how the request will be executed (if set to false, the request is made synchronously, if true - asynchronously ).
Useful links to explore: