Wie mache ich eine HTTP-Anfrage in Javascript und PHP?

Dec 15 2022
Um eine HTTP-Anforderung in JavaScript zu stellen, können Sie das XMLHttpRequest-Objekt oder die neuere Abruf-API verwenden. Hier ist ein Beispiel für die Verwendung von XMLHttpRequest: Beachten Sie, dass die Abruf-API nur in modernen Browsern unterstützt wird, sodass Sie möglicherweise ein Polyfill verwenden oder für ältere Browser auf XMLHttpRequest zurückgreifen müssen.

Um eine HTTP-Anfrage in JavaScript zu stellen, können Sie das XMLHttpRequestObjekt oder die neuere fetchAPI verwenden.

Hier ist ein Beispiel mit 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));

Beachten Sie, dass die fetchAPI nur in modernen Browsern unterstützt wird, sodass Sie möglicherweise eine Polyfüllung verwenden oder auf die Verwendung XMLHttpRequestfür ältere Browser zurückgreifen müssen.

Und um eine HTTP-Anfrage in PHP zu stellen, können Sie die eingebaute Funktion file_get_contents() oder die robustere cURL-Bibliothek verwenden.

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