In this repository I will try to collect the most common use cases of sending request using JavaScript.
I will give examples for the following approaches:
I will use JSONPlaceholder service for requests testing and CodePen for code examples (open Console Panel)
XMLHttpRequest API
[example]
let request = new XMLHttpRequest();
request.addEventListener("load", function () {
console.log(
JSON.parse(this.responseText)
);
});
request.open("GET", "https://jsonplaceholder.typicode.com/todos/1");
request.send();
Fetch API
[example]
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
jQuery Ajax
[example]
$.get('https://jsonplaceholder.typicode.com/todos/1', function (response) {
console.log(response);
});
Axios
[example]
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(function (response) {
console.log(response.data);
});
Response
Object {
completed: false,
id: 1,
title: "delectus aut autem",
userId: 1
}