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
pre element to display the fetched data.
- The
script.js file is linked at the end of the body.
-
JavaScript:
- An event listener is added to the button, which triggers the fetch request when clicked.
- The
fetch function is used to send a GET request to the specified API endpoint.
- The response is then converted to JSON format and displayed in the
pre element.
- Any errors during the fetch process are caught and logged to the console, and an error message is displayed in the
pre element.
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.
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
fetchAPI to make these requests. Here's a simple example of how you can do this:HTML
JavaScript (script.js)
Explanation
HTML:
preelement to display the fetched data.script.jsfile is linked at the end of the body.JavaScript:
fetchfunction is used to send a GET request to the specified API endpoint.preelement.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.