Jak wykonać żądanie HTTP w Javascript i PHP?

Dec 15 2022
Aby wysłać żądanie HTTP w JavaScript, możesz użyć obiektu XMLHttpRequest lub nowszego interfejsu API pobierania. Oto przykład użycia XMLHttpRequest: Zwróć uwagę, że interfejs API pobierania jest obsługiwany tylko w nowoczesnych przeglądarkach, więc może być konieczne użycie funkcji polyfill lub powrót do XMLHttpRequest w starszych przeglądarkach.

Aby wykonać żądanie HTTP w JavaScript, możesz użyć XMLHttpRequestobiektu lub nowszego fetchinterfejsu API.

Oto przykład użycia 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));

Pamiętaj, że fetchinterfejs API jest obsługiwany tylko w nowoczesnych przeglądarkach, więc może być konieczne użycie funkcji polyfill lub powrót do korzystania XMLHttpRequestze starszych przeglądarek.

Aby wykonać żądanie HTTP w PHP, możesz użyć wbudowanej funkcji file_get_contents() lub bardziej rozbudowanej biblioteki cURL.

Używając 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);
?>