¿Cómo hago una solicitud HTTP en Javascript y PHP?
Dec 15 2022
Para realizar una solicitud HTTP en JavaScript, puede usar el objeto XMLHttpRequest o la API de búsqueda más reciente. Aquí hay un ejemplo usando XMLHttpRequest: Tenga en cuenta que la API de búsqueda solo es compatible con los navegadores modernos, por lo que es posible que deba usar un relleno múltiple o recurrir al uso de XMLHttpRequest para navegadores más antiguos.
Para realizar una solicitud HTTP en JavaScript, puede usar el XMLHttpRequestobjeto o la fetchAPI más nueva.
Aquí hay un ejemplo usando XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.example.com/', true);
xhr.onload = function() {
if (this.status == 200) {
var data = JSON.parse(this.response);
console.log(data);
}
};
xhr.send();
fetch('https://www.example.com/')
.then(response => response.json())
.then(data => console.log(data));
Tenga en cuenta que la fetchAPI solo es compatible con los navegadores modernos, por lo que es posible que deba usar un polyfill o recurrir a XMLHttpRequestnavegadores más antiguos.
Y para realizar una solicitud HTTP en PHP, puede usar la función integrada file_get_contents() o la biblioteca cURL más robusta.
Usando file_get_contents():
<?php
// Set the URL of the request
$url = 'http://www.example.com';
// Send the request and store the response
$response = file_get_contents($url);
// Check for errors
if($response === false) {
// Handle error
} else {
// Use the response
}
?>
<?php
// Initialize cURL
$ch = curl_init();
// Set the URL of the request
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
// Send the request and store the response
$response = curl_exec($ch);
// Check for errors
if(curl_errno($ch)) {
// Handle error
} else {
// Use the response
}
// Close the cURL handle
curl_close($ch);
?>
![¿Qué es una lista vinculada, de todos modos? [Parte 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































