从服务器获得响应后未附加JSON

时间:2019-05-19 21:45:16

标签: javascript php ajax

我正试图从我的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

0 个答案:

没有答案