无法使用AngularJS $ http.get从000webhost服务器获取JSON数据

时间:2016-09-02 21:16:58

标签: javascript php angularjs json

我正在尝试从HTML服务器中获取数据。

我尝试w3 schools code但是当我尝试使用我的服务器链接时,它什么都没打印。

这是角度代码:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>     
<div ng-app="myApp" ng-controller="customersCtrl">

  <table>
    <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
    </tr>
  </table>

</div>

<script>
  var app = angular.module('myApp', []);
  app.controller('customersCtrl', function($scope, $http) {
    $http
      .get("http://rabikhan.net23.net/Bitm_Student_Project/src/test.php")
      .then(function (response) {$scope.names = response.data.records;});
  });
</script>

和php代码

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("mysql4.000webhost.com", "a1724083_rhk", "r7224191", "a1724083_tour2");

$result = $conn->query("SELECT CompanyName, City, Country FROM customers");

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
  if ($outp != "") {$outp .= ",";}
  $outp .= '{"Name":"'  . $rs["CompanyName"] . '",';
  $outp .= '"City":"'   . $rs["City"]        . '",';
  $outp .= '"Country":"'. $rs["Country"]     . '"}'; 
}
$outp ='{"records":['.$outp.']}';
$conn->close();

echo($outp);
?>

问题

如何echo($outp);打印所需信息?

1 个答案:

答案 0 :(得分:0)

将您的php更改为:

&#13;
&#13;
<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");

    $conn = new mysqli("mysql4.000webhost.com", "a1724083_rhk", "r7224191", "a1724083_tour2");

    $result = $conn->query("SELECT CompanyName AS Name, City, Country FROM customers");

    // create an empty output array
    $output = array();
    while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
        // add record to output array
        $output.push($rs); 
    }

    $conn->close();

    // return output array as proper json
    echo json_encode($output);
?>
&#13;
&#13;
&#13;

我还注意到您的php响应中有一些指向Doogal的分析代码,请确保不将其附加到您的JSON响应中