To make an HTTP request in JavaScript, you can use the XMLHttpRequest
object or the fetch()
function. Here's an example using XMLHttpRequest
:
HTTP request using XMLHttpRequest Example
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.example.com/', true);
xhr.onload = function () {
// do something with response data
console.log(this.responseText);
};
xhr.send();
Here's an example to make an HTTP request in JavaScript using fetch()
:
Using fetch() Example
fetch('http://www.example.com/')
.then(response => response.text())
.then(data => {
// do something with response data
console.log(data);
});
Both of these examples make a GET
request to the specified URL. You can replace GET
with POST
or another HTTP method to make a different type of request.
It's worth noting that fetch()
is more modern and is generally preferred over XMLHttpRequest
, but it may not be supported in older browsers. If you need to support older browsers, you may want to use XMLHttpRequest
.
Related:
- Execute JavaScript using Nashorn in the Console
- How to Remove Blank Lines From Textarea using JavaScript?