-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
demo: api fetch
a static HTML page can query an API using JavaScript. This is commonly done through AJAX (Asynchronous JavaScript and XML) requests. With modern JavaScript, you can use the fetch API to make these requests. Here's a simple example of how you can do this:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Query Example</title>
</head>
<body>
<h1>API Query Example</h1>
<button id="fetchData">Fetch Data</button>
<pre id="result"></pre>
<script src="script.js"></script>
</body>
</html>JavaScript (script.js)
document.getElementById('fetchData').addEventListener('click', () => {
fetch('https://api.example.com/data') // Replace with your API endpoint
.then(response => response.json())
.then(data => {
document.getElementById('result').textContent = JSON.stringify(data, null, 2);
})
.catch(error => {
console.error('Error fetching data:', error);
document.getElementById('result').textContent = 'Error fetching data';
});
});Explanation
-
HTML:
- A simple HTML structure with a button and a
preelement to display the fetched data. - The
script.jsfile is linked at the end of the body.
- A simple HTML structure with a button and a
-
JavaScript:
- An event listener is added to the button, which triggers the fetch request when clicked.
- The
fetchfunction is used to send a GET request to the specified API endpoint. - The response is then converted to JSON format and displayed in the
preelement. - Any errors during the fetch process are caught and logged to the console, and an error message is displayed in the
preelement.
This example assumes the API endpoint supports CORS (Cross-Origin Resource Sharing) if it's a different origin from where your HTML page is served. If the API does not support CORS, you'll need to handle that on the server-side or use a proxy server.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels