Come posso effettuare una richiesta HTTP in Javascript e PHP?

Dec 15 2022
Per effettuare una richiesta HTTP in JavaScript, puoi utilizzare l'oggetto XMLHttpRequest o la nuova API fetch. Ecco un esempio che utilizza XMLHttpRequest: Nota che l'API fetch è supportata solo nei browser moderni, quindi potrebbe essere necessario utilizzare un polyfill o utilizzare XMLHttpRequest per i browser meno recenti.

Per effettuare una richiesta HTTP in JavaScript, puoi utilizzare l' XMLHttpRequestoggetto o l' fetchAPI più recente.

Ecco un esempio 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));

Si noti che l' fetchAPI è supportata solo nei browser moderni, quindi potrebbe essere necessario utilizzare un polyfill o ricorrere all'utilizzo XMLHttpRequestper i browser meno recenti.

E per effettuare una richiesta HTTP in PHP, puoi utilizzare la funzione integrata file_get_contents() o la più robusta libreria cURL.

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);
?>