Learn Dynamic HTML With JS
Lesson 1 - HTML JS Relationship
Lesson 2 - HTML DOM
Lesson 3 - Browser BOM
Lesson 4 - Basic Interaction
Lesson 5 - Manipulating CSS
Lesson 7 - Form Handling
The GET method is a widely-used HTTP request method for retrieving data from a server. It is typically used to fetch resources such as HTML documents, images, or data from APIs. Compared to other methods like POST, GET requests are simpler in structure and are faster for retrieving data. However, they are less secure for sending sensitive information because parameters are visible in the URL.
In JavaScript, you can perform a GET request using XMLHttpRequest()
or the newer fetch()
API to asynchronously retrieve data from a server.
Here's an example using XMLHttpRequest()
:
<!DOCTYPE html> <html> <head> <title>GET Request</title> </head> <body> <p id="responseMessage"></p> <script> const xhttp = new XMLHttpRequest(); xhttp.onload = function() { document.getElementById("responseMessage").innerHTML = this.responseText; }; xhttp.open("GET", "https://jsonplaceholder.typicode.com/posts"); xhttp.send(); </script> </body> </html>
In this example:
XMLHttpRequest()
named xhttp
.onload
function that executes when the request completes successfully. It updates the HTML content of an element with the response received (this.responseText
).xhttp.open()
to specify the HTTP method (GET) and the URL of the resource (https://jsonplaceholder.typicode.com/posts
).xhttp.send()
initiates the request to fetch data from the specified URL.This illustrates how JavaScript can be used to asynchronously fetch and display data from a server using a GET request.