Fetching data from a server
Fetching data from a server is a common task in web development, and JavaScript provides the fetch API to make this process straightforward.
1. Basic Fetch Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetching Data from Server</title>
</head>
<body>
<div id="dataContainer"></div>
<script>
// Fetching data from a server
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => {
// Accessing an element to display the fetched data
var container = document.getElementById('dataContainer');
container.textContent = 'Title: ' + data.title;
})
.catch(error => console.error('Error:', error));
</script>
</body>
</html>
In this example, we use the fetch function to make a GET request to a JSONPlaceholder endpoint. We handle the response using the then method, converting the response to JSON. Finally, we update the content of an HTML element with the fetched data.
2. Handling API with Parameters:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetching Data with Parameters</title>
</head>
<body>
<div id="userData"></div>
<script>
// Fetching user data with parameters
var userId = 1;
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(response => response.json())
.then(user => {
var userData = document.getElementById('userData');
userData.innerHTML = `
<p>Name: ${user.name}</p>
<p>Email: ${user.email}</p>
<p>Username: ${user.username}</p>
`;
})
.catch(error => console.error('Error:', error));
</script>
</body>
</html>
In this example, we include a parameter (user ID) in the URL to fetch specific user data.