首页 > 解决方案 > 从服务器获得响应后,未附加 JSON

问题描述

我正在尝试从我的 web 服务页面获取一组 json,这些页面单独运行良好。我的问题是在我发出 ajax 请求后,没有附加 json 数据。

这是 web-service.php 页面

    $query = "SELECT * FROM courses ;";
    $result = mysqli_query($db, $query);
    $q = "SELECT COUNT(*) FROM courses";
    $num_of_rows = mysqli_query($db, $q);
    $number = mysqli_fetch_array($num_of_rows);

    $counter = 0;
    print('{"lenght":"');
    print $number['COUNT(*)'];
    print('",');
    print('"data":[');
    while ($row = @mysqli_fetch_array($result)) {
      echo json_encode($row);
      if ($counter === ($number['COUNT(*)'] - 1)) { } else {
        print(",");
      }
      $counter++;
    }
    print("]}");

这是 home.js 中的 ajax 请求

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
     if (this.readyState == 4 && this.status == 200) {
       var json = JSON.parse(this.responseText);
       $("#courses").append(json);        
     } else {
       console.log("readyState "+this.readyState);
       console.log("status "+this.status);
     }
    };
    xhttp.open("GET", "./web-service.php", true);
    xhttp.send();

控制台显示了这个

    readyState 1         home.js:35:9
    status 0             home.js:36:9
    readyState 2         home.js:35:9
    status 200           home.js:36:9
    readyState 3         home.js:35:9
    status 200           home.js:36:9

标签: javascriptphpajax

解决方案


推荐阅读