How to Get HTTP GET Request in JavaScript?

18-Apr-2023

.

Admin

How to Get HTTP GET Request in JavaScript?

This tutorial will give you example of http get request in javascript. you'll learn how to make http get request in javascript. We will use html - http get request with javascript. we will help you to give example of how to get http status from javascript. Here, Creating a basic example of javascript - how to use http to return the status of a url.

To get an HTTP GET request in JavaScript, you can use the XMLHttpRequest object. Here is an example:

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Get HTTP GET Request in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

var xhr = new XMLHttpRequest();

xhr.open('GET', 'http://example.com/api/data', true);

xhr.onload = function () {

if (xhr.readyState === 4 && xhr.status === 200) {

var data = JSON.parse(xhr.responseText);

console.log(data);

}

};

xhr.send();

</script>

</html>

In this example, we create a new XMLHttpRequest object and set the method to GET and the URL to 'http://example.com/api/data'. We also set the async parameter to true, which means that the request will be sent asynchronously.

Next, we define an onload function that will be called when the request completes. In this function, we check that the readyState is 4 (which means that the request is complete) and that the status is 200 (which means that the server responded with a success status code).

If both of these conditions are met, we parse the response text as JSON and log it to the console.

Finally, we call xhr.send() to send the request.

#JavaScript