[英]Can't get JSON data from 000webhost server with AngularJS $http.get
我正在嘗試從服務器以HTML文件形式獲取數據。
我嘗試了w3學校代碼,但是當我嘗試使用服務器鏈接時,它什么也不會打印。
這是角度代碼:
<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);
打印所需的信息?
將您的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 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); ?>
我還注意到,您的php響應中有一些分析代碼指向http://stats.hosting24.com/count.php ,請確保不要將其附加到JSON響應中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.