Praxisbeispiel: Daten von einer PHP-Anwendung anfordern

14.4 AJAX – XMLHTTPRequest – Kommunikation mit dem Server Daten von einer PHP-Anwendung abholen.

<div id="demo"></div>
const xhr = new XMLHttpRequest();
xhr.open("POST", "app.php");
xhr.onreadystatechange = function() {
   console.log (this.readyState);
   if (this.readyState === 4 && this.status === 200) {
      const myObj = JSON.parse(this.responseText);
      console.log ("myObj", myObj, typeof myObj);

      document.getElementById("demo").innerHTML = 
         `Studentin: ${myObj.student} <br>
          Alter: ${myObj.alter} <br>
          Note: ${myObj.note}`;
   }
}

xhr.send();
myObj {student: 'Sara', alter: 21, note: 2} object

Für das Beispiel wird ein Webserver und eine PHP-Anwendung zum Aussenden der Daten gebraucht. So würde eine einfache PHP-Anwendung aussehen:

<?php
$obj = new stdClass;
$obj->student = "Sara";
$obj->alter = 21;
$obj->note = 2;

echo json_encode($obj);
?>