Fetch API and AJAX
JavaScript allows you to communicate with servers to fetch or send data
without reloading the web page. This technique is called AJAX (Asynchronous JavaScript and XML),
and the modern way to do it is with the Fetch
API.
Making HTTP Requests
The Fetch API uses the fetch()
function to
make HTTP requests and retrieve resources such as JSON data.
fetch(
"https://api.example.com/data")
.
then(
response => response.
json())
// Parse JSON from response
.
then(
data => {
console.
log(data);
// Use the fetched data here
})
.
catch(
error => {
console.
error(
"Error fetching data:", error);
});
Fetching JSON Data from API
JSON (JavaScript Object Notation) is a lightweight data
format used to store and exchange data. It’s easy for humans to read and write,
and easy for machines to parse and generate.
Key points about JSON:
·
Format: JSON represents data as key-value pairs, much
like a dictionary or map.
·
Data types: It supports strings, numbers, booleans (true
/false
),
arrays (lists), objects (nested key-value pairs), and null
.
·
Structure: Data is wrapped inside curly braces {}
for
objects, and square brackets []
for arrays.
·
Language independent: Although JSON originated from JavaScript,
it is language-agnostic and widely used for data exchange between servers and
web apps, APIs, databases, etc.
Example:
{
"name":
"Alice",
"age":
25,
"isStudent":
true,
"hobbies":
["reading",
"music",
"hiking"]
}
·
"name"
is a
key and "Alice"
is
its string value.
·
"age"
has a
number value.
·
"isStudent"
has a boolean value.
·
"hobbies"
is an array containing strings.
The .json()
method on the response object
converts the raw response into a JavaScript object, making it easy to work
with.
fetch(
"https://api.example.com/users")
.
then(
response => response.
json())
.
then(
users => {
users.
forEach(
user => {
console.
log(user.
name);
});
});
.then()
Chaining
The Fetch API returns a Promise, which lets you chain multiple .then()
calls to handle asynchronous operations in order.
fetch(
"https://api.example.com/posts")
.
then(
response => {
if (!response.
ok) {
throw
new
Error(
"Network response was not ok");
}
return response.
json();
})
.
then(
posts => {
console.
log(posts);
})
.
catch(
error => {
console.
error(
"Fetch error:", error);
});