Standard formats to send data over the internet and receive it
eXtensible Markup Language
XML
uses tags to define its structure similar to
HTML
and SVG
.
Tags are not predefined, you can specify your own tags.
Nested tags are possible.
<person>
<name>Susanne</name>
<surname>Koenig</surname>
<nationality>German</nationality>
<languages>
<language>German</language>
<language>English</language>
</languages>
</person>
JavaScript Object Notation
JSON
is a lightweight, readable format for structuring
data.
It is a modern alternative to XML to transmit data from server to client.
JSON is a string whose format very much resembles JavaScript objects.
{
"name" : "Susanne",
"surname" : "Koenig",
"nationality" : "German",
"languages" : ["German", "English"]
}
Like a JS object JSON maps keys to values.
Always use double quotes ""
in JSON.
const obj = JSON.parse('{"name": "Susanne","surname": "Koenig"}');
let myJSON = JSON.stringify(obj);
JSON.parse()
is a built-in JavaScript method to turn
JSON into a
JavaScript object.
JSON.stringify()
is a built-in JavaScript method to
turn a JavaScript object into a
JSON.
HTTP can also fetch only one part of documents to update web pages on demand. Without reloading.
Google came up with that in 2006.
Asynchronous JavaScript and XML
It combines a group of existing technologies: HTML, CSS, JavaScript, XML, JSON, etc.
Together this group can build modern applications.
XMLHttpRequest
Also known as XHR API is used to make a request to a server.
API: Application Programming Interface is a set of methods which specify the rules of communication between two interested parties.
Note: The incoming data does not need to be in
XML
.
var request = new XMLHttpRequest();
request.open('GET', '/path/to/api', true);
request.setRequestHeader('Content-type', 'application/json'); // Not for text + HTML
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
console.log(JSON.parse(request.responseText));
} else {
// We reached our target server, but it returned an error
}
});
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(data => console.log(data));
fetch
json()
to parse the responseA promise is an object that may produce a single value some time in the future. Either a resolve value, or a reason why it's not resolved (rejected).
const promise = new Promise((resolve, reject) => {
let number = 6 + 4;
if(number === 10) {
resolve("Promise was fulfilled");
} else {
reject();
}
});
promise
.then(result => console.log(result))
.catch(() => alert("Promise was rejected"));
button.addEventListener("click", submitForm);
Once the button is clicked, the function submitForm will be called.
movePlayer(100, "left", function(){
movePlayer(200, "right", function(){
movePlayer(400, "left", function(){
});
});
});
Once the player moved 100 steps to the left and that is done, the player should move 200 steps to the right and then this move is done, the player moves 400 steps to the left again.
= pyramid of doom (repetition of code, difficult to read)
movePlayer(100, "left")
.then(() => movePlayer(200, "right"))
.then(() => movePlayer(400, "left"));
Better, but still hard to read
const promise = new Promise((resolve, reject) => {
let number = 6 + 4;
if(number === 10) {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
});
promise.then(result => console.log(result))
promise
.then(result => result + "!")
.then(result2 => result2 + "?")
.then(result3 => {
throw Error;
console.log(result3)
})
.catch(() => console.log("error!"));
Promises are used for asynchronous JavaScript.
The dot syntax here is called chaining
To understand asynchronous JavaScript, we need to understand synchronous JavaScript first.
Until now all our JS was synchronous: you run some code and the result will be returned as soon as the browser can do it.
While an operation is processed (calling a function for example),
nothing else can happen - remember alert
?
Reason for that is that JS is single-threaded. All tasks run on the main thread like pearls on a necklace.
Often you need to wait inside a function for something to happen, for a response, before you can move on.
If you fetch
an image from a server via JS for example,
you cannot use that image right away - it has not been downloaded
yet.
Application Programme Interface
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(data => console.log(data));
fetch
json()
to parse the responseRewriting code to improve it and make it cleaner is refactoring.
It is rare to design a program correctly on first go.
One basic principle of code refactoring.
You can achieve that by
Refactoring code always involves several steps to ensure that the working code does not break accidentally.
Break the change down in to small, independent steps that should each be safe. At each stage you test the change and make sure that things still work.
If they don't work then it's very easy to go back and undo the last small change you made, or review it to see what went wrong.