@dagoeos The response
property may be one of many different data types including, but not limited to a string. Using responseText
makes it clear that you’re after the text version of the data, even though it will likely be the same value as response
in this case.
That being said, a valid response type is “json” which is our target format for this data, so if we wanted to have that parsing happen automatically, we could set the responseType
, skip JSON.parse
, and pull directly from xhr.response
.
var xhr = new XMLHttpRequest();
xhr.responseType = "json"; // xhr.response will be parsed into a JSON object
xhr.open('GET', "https://ipinfo.io/json", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.response.ip); // no parsing needed
}
}