Requisição JavaScript Opcoes
Requisição JavaScript Opcoes
or the more modern `fetch` API. Here's an example of how to use both methods: Using
XMLHttpRequest: ```javascript var xhr = new XMLHttpRequest(); xhr.open('GET',
'https://api.example.com/data', true); xhr.onreadystatechange = function() { if (xhr.readyState
=== 4 && xhr.status === 200) { var response = JSON.parse(xhr.responseText); // Do
something with the response data console.log(response); } }; xhr.send(); ``` Using fetch:
```javascript fetch('https://api.example.com/data') .then(function(response) { if (response.ok) {
return response.json(); } throw new Error('Network response was not ok.'); })
.then(function(data) { // Do something with the response data console.log(data); })
.catch(function(error) { // Handle any errors console.error(error); }); ``` In both examples, an
HTTP GET request is made to `https://api.example.com/data`. You can replace this URL with
the actual endpoint you want to request. The response from the server is processed within
the `onreadystatechange` callback (for `XMLHttpRequest`) or through the promise chain (for
`fetch`), and you can access the response data and handle any errors accordingly.
Or
To make an HTTP request in JavaScript, you can use the built-in `XMLHttpRequest` object
or the newer `fetch` API. Here's an example of how to make an HTTP GET request using
both approaches: Using XMLHttpRequest: ```javascript var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true); xhr.onreadystatechange = function() { if
(xhr.readyState === 4 && xhr.status === 200) { var response =
JSON.parse(xhr.responseText); // Process the response data here console.log(response); }
}; xhr.send(); ``` Using fetch API: ```javascript fetch('https://api.example.com/data')
.then(function(response) { if (response.ok) { return response.json(); } else { throw new
Error('Network response was not ok.'); } }) .then(function(data) { // Process the response
data here console.log(data); }) .catch(function(error) { // Handle errors here
console.log('Error:', error.message); }); ``` Both examples demonstrate a basic GET request
to `https://api.example.com/data`. You can replace the URL with the desired endpoint you
want to send the request to. Additionally, you can modify the code to handle different HTTP
methods (e.g., POST, PUT, DELETE) and pass any necessary data or headers along with
the request.