简体   繁体   中英

Can't receive PHP object by using AJAX

I can't fetch the php file from the ajax. Firstly an object is created in the PHP file, then it is converted into JSON by using json_encode() function. The problem is: when I request that PHP file from ajax, nothing is shown as an output. ('Smith' is supposed to be an output though)

Here is my php file: 1.php

 <?php 
    $myObj->name = "Smith";
    $myObj->age = 20;
    $myObj->Address = "Yangon";

    $myJSON = json_encode($myObj);

    echo "$myJSON"; 
  ?>

Here is ajax file: ajaxfile.php

<p id="demo"></p>
<script type="text/javascript">
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            document.getElementById("demo").innerHTML = myObj.name;
        }
    };
    xmlhttp.open("GET", "1.php", true);
    xmlhttp.send();
</script>

Try

<?php
  $myObj['name'] = "Smith";
  $myObj['age'] = 20;
  $myObj['Address'] = "Yangon";
  $myJSON = json_encode($myObj);

  echo "$myJSON";
 ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM