To get JSON content, you need to use the response JSON type, which isn't quite difficult to use. To fetch https://con-se.glitch.me/res/searchme.json
, here's what you would do initially:
fetch('https://con-se.glitch.me/res/searchme.json')
But now all you have is a promise, no actual content. Here's where the then
function comes in. You'll need two:
.then(response => response.json())
.then(json => {
console.table(json);
})
If you want, you can also see keys individually, like json.key
will contain the value of "key"
.
But what if there's an error?
Well, that's where the catch
function comes in.
.catch(err => console.error(err))
This will log an error in the console should an error occur.
Plain text or HTML is very similar to parsing JSON. The fetch
statement would be just the same, but without a JSON file (or with it, if you just want to get the plain text JSON.)
Here are the then
functions that would be required:
.then(response => response.text())
.then(html => {
console.log(html);
})
The catch function would be identical.
XHRs are much less concise, but, for me, they are much easier to understand.
Keep in mind that XHR is older and most people don't use it anymore :(
- XHR stands for XMLHttpRequest.
- XHR is a function using
this
, so it will be stored in a variable.
To create a new XHR, you'll need a variable:
var xhr = new XMLHttpRequest();
But, obviously, nothing's going to happen. You need to use XMLHttpRequest().open
for this.
xhr.open('GET', 'https://con-se.glitch.me/res/searchme.json', true)
But still nothing happens. You need your onload
and onerror
values.
Create an anonymous function.
xhr.onload = function() {}
You're going to need to check if the response is ok. Put the following inside the anonymous function:
if (xhr.status >= 200 && xhr.status < 300) {
var data = JSON.parse(xhr.responseText);
// Handle the JSON here
console.table(data);
} else {
console.log('Failed with status ' + xhr.status);
}
Then you're going to need your onerror
value.
xhr.onerror = function(err) {}
Then, handle the error by putting this in the anonymous function:
console.error('XHR Error: ' + err);
Send the request:
xhr.send();
Check if the response is ok:
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.responseText);
} else {
console.log('Failed with error ' + xhr.status);
}
You're going to need your onerror
value:
xhr.onerror = function(err) {
console.error('XHR Error: ' + err)
}
Send the request:
xhr.send();