从 php 文件获取 JSON 数组

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h1>从 PHP 文件获取 JSON 数据,并把它转换为 JavaScript 数组</h1>
  6.  
  7. <p id="demo"></p>
  8.  
  9. <script>
  10. var xmlhttp = new XMLHttpRequest();
  11. xmlhttp.onreadystatechange = function() {
  12. if (this.readyState == 4 && this.status == 200) {
  13. var myObj = JSON.parse(this.responseText);
  14. document.getElementById("demo").innerHTML = myObj[2];
  15. }
  16. };
  17. xmlhttp.open("GET", "/demo/demo_php_json_encode_array.php", true);
  18. xmlhttp.send();
  19. </script>
  20.  
  21. </body>
  22. </html>