To call a Web API from an HTML button, you can use JavaScript and the XMLHttpRequest (XHR) object, which allows you to make HTTP requests to a server. Here are the basic steps:
- Create an HTML button and add an event listener to it. You can do this using the
addEventListener
method.
html<button id="myButton">Click me</button>
<script>
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
// Code to call the Web API goes here
});
</script>
- In the event listener, create an XHR object using the
XMLHttpRequest
constructor.
javascriptconst xhr = new XMLHttpRequest();
- Open a connection to the Web API using the
open
method. The first argument is the HTTP method (e.g. GET or POST), and the second argument is the URL of the Web API.
javascriptxhr.open("GET", "http://example.com/api/data");
- Set any request headers that are required. This is optional, but may be necessary if your Web API requires certain headers to be present.
javascriptxhr.setRequestHeader("Authorization", "Bearer token123");
- Set a callback function to be executed when the request completes. This is done using the
onreadystatechange
property of the XHR object.
javascriptxhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
// Code to handle the response goes here
}
};
- Send the request using the
send
method.
javascriptxhr.send();
This is a basic example of how to call a Web API from an HTML button using JavaScript and XHR. Depending on your requirements, you may need to modify this code to handle different HTTP methods, request and response formats, and error handling.
Comments
Post a Comment