当我的Angular应用调用我的php文件时,我收到[$ http:baddata]错误。 我不确定错误的确切位置在哪里,但我相信这是构建json对象的问题!我附上了所有相关代码。任何帮助都会很棒。在此先感谢:)
这是连接到我的数据库并试图将JSON格式字符串返回给调用文件的PHP文件
<?php
echo '<script>console.log("Inside php file!")</script>';
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once('mysqli_connect.php');
$query = "SELECT rideid, destination, price, capacity, userid, origin, departDate, vehicle FROM rides";
$result = @mysqli_query($dbc, $query);
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"Origin":"' . $rs["origin"] . '",';
$outp .= '"Destination":"' . $rs["destination"] . '",';
$outp .= '"Price":"'. $rs["price"] . '"}';
$outp .= '"Capacity":"'. $rs["capacity"] . '"}';
}
$outp ='{"records":['.$outp.']}';
//echo '<script>console.log(JSON.stringify('.$outp.'))</script>';
$conn->close();
echo($outp);
这是向PHP文件发出请求的Angular应用
<html>
<head>
<!-- Include Angular -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
</head>
<body>
<!-- Ride Table -->
<div ng-app = "rideAppTest" ng-controller= "rideCtrlTest">
<table>
<tr ng-repeat = "x in names">
<td>{{x.Origin}}</td>
<td>{{x.Destination}}</td>
<td>{{x.Price}}</td>
<td>{{x.Capacity}}</td>
</tr>
</table>
</div>
<!-- End Ride Table -->
<!--Ride Table Script-->
<script>
var app = angular.module('rideAppTest', []);
app.controller('rideCtrlTest', function($scope, $http) {
$http.get("angularFilter.php")
.then(
function (response) {
$scope.names = response.data.records;
},
function(data){
console.log("Error!" + data);
}
);
});
</script>
</body>
</html>
答案 0 :(得分:2)
不要按照你的方式构建JSON,首先收集数组或对象内的所有内容,然后执行echo json_encode($result);
这样的事情:
$outp = [];
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = $rs;
}
echo json_encode(["records" => $outp]);
答案 1 :(得分:0)
感谢@Madhav的帮助。最终为我工作的是:)
while($rs = mysqli_fetch_array($result)) {
$myArray[] = array(
'Origin' => $rs["origin"],
'Destination' => $rs["origin"],
'Price' => $rs["price"],
'Capacity' => $rs["capacity"]
);
}
echo json_encode(["records" => $myArray]);