2. PHP-Sample with a class in PHP

HTML-Teil

    <script type="text/javascript">
       // <![CDATA[
      "use strict";

      var xmlhttp = new XMLHttpRequest();
       // verbinde XMLHttpRequest mit der "Event-Methode"
      xmlhttp.onreadystatechange = readajax;

      function  testajax( form ) {
        "use strict";
          // Aufruf 
         xmlhttp.open("GET", "TestAjax01.php?parameter=wert");
         xmlhttp.send(null);
      }

       function readajax() {
         "use strict";
         var elementajax = document.getElementById("ajax");
         if (xmlhttp.readyState == 4) {
           alert(xmlhttp.responseText);
           var obj = JSON.parse(xmlhttp.responseText); 
           elementajax.innerHTML = '<ul>'+'<li>'+obj.name+'</li>' + '<li>' + obj.mnr+'</li>'+'</ul>';
         }
         else {
           alert(xmlhttp.readyState);
         }
       }

      // ]]>
    </script>

  </head>

<body>
  <form>
    <input type="button" value="Send" onclick="testajax(this.form)"/>
  </form>
   <div id="ajax"> </div>
</body>
</html>
</div>

PHP-Teil

<?php

  class Student {
    public $name="";
    public $mnr=1;


    private function processArray($array) {
        foreach($array as $key => $value) {
            if (is_object($value)) {
                $array[$key] = $value->toArray();
            }
            if (is_array($value)) {
                $array[$key] = $this->processArray($value);
            }
        }
        // If the property isn't an object or array, leave it untouched
        return $array;
    }

    public function toArray() {
        return $this->processArray(get_object_vars($this));
    }

  }  // Student


  $std = new Student;
  $std->setName($name);
  $std->setMnr($mnr);

   $ergebnis = json_encode($std->toArray());
   echo $ergebnis;


?>
 





Druckbare Version


1. PHP Sample
1. JSP Sample