AJAX enables
Asynchronous JavaScript And XML
[0] http://adaptivepath.org/ideas/ajax-new-approach-web-applications/
(corrected for modern use)
Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:
standards-based presentation using
XHTMLHTML and CSSdynamic display and interaction using the Document Object Model
data interchange and manipulation using
XML and XSLTJSONasynchronous data retrieval using
XMLHttpRequestFetchand JavaScript binding everything together.
open(), then call send()
readyState property of the request and error checking is cumbersomevar httpRequest;
function sendRequest() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = printResponse;
httpRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');
httpRequest.send();
}
function printResponse() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
console.log(httpRequest.responseText);
} else {
console.log('There was a problem: ' + httpRequest.status);
console.log({httpRequest})
}
}
}
The Fetch interface is concise
https://jsonplaceholder.typicode.com/posts/1
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
console.log(response.status);
return response.text(); // body is not quite ready yet
})
.then(function(text) {
console.log(text); // now the body is ready
});
fetch() takes at least one argument, the URL of the resource to fetchfetch returns a Promise, to which you add a series of callbacks using the then methodfetch then calls the server, just like you did in the address bar abovefetch calls your callbacks in orderthen gets called once the HTTP headers of the response are availableresponse.text(), which returns another promise
then gets called after the entire body has been received
let postNumber = 1;
fetch('https://jsonplaceholder.typicode.com/posts/' + postNumber)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
response.json() is an alternative to response.text()
response.json parses the body of the response as JSON and returns real JavaScript objectsthen receives a proper JavaScript Object which is the result of calling JSON.parse() on the bodyIf you want to request data from a local webserver, use a partial URL
fetch('/city-market.md')
.then(function(response) {
return response.text();
})
.then(function(myText) {
console.log(myText);
});
then function happens to return response.text() because it is a Markdown fileresponse.json()
.catch(function(error) { do_something_here })
catch
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
if (!response.ok) {
console.log('HTTP error: ' + response.status);
} else {
return response.json();
}
})
.then(function(json) {
console.log(json);
})
.catch(function(error) {
console.error('Network error:\n', error);
});
See a more comprehensive JSON lesson here: JSON lesson
{"userId": 1,
"id": 1,
"title": "My most amazing post",
"body": "This is my first post, isn't it great. Maybe I'll write some more."
}
The Fetch API converts text into JSON for you if you call response.json()
but if you want to do it yourself...
JSON.parse converts a string into an object:
let data = JSON.parse(string)
So this would work fine:
fetch('/city-market.json')
.then(function(response) {
return response.text();
})
.then(function(myText) {
let myObject = JSON.parse(myText);
console.log(myObject);
});
/