我是 AngularJS 的新手。我正在开发一个项目,其中应用程序使用 PHP 和 AngualarJS 在 HTML 表中显示来自 MYSQL 的内容(带有航类详细信息的虚拟表,其中包含航空公司、出发、到达、持续时间和价格列)。我已经为 AngularJs 和 PHP 编写了代码。现在,当我尝试将检索到的数据显示为 html 时,我无法这样做(我试图直接访问我的 PHP 文件,它以 JSON 格式显示数据)。请查看我的 HTML(flights.html), JAVASCRIPT/AngularJS(Flights.js) 和 PHP(Flights.php) 代码:
HTML 代码
<!DOCTYPE html>
<html ng-app="mymodule">
<head>
<title>Flights</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="Flights.js" type="text/javascript"></script>
</head>
<body ng-controller="myCtrl">
<table>
<thead>
<tr>
<th>Airlines</th>
<th>Departure</th>
<th>Arrival</th>
<th>Duration</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr ng-repeat = "flights in response">
<td>{{flights.Airlines}}</td>
<td>{{flights.departure}}</td>
<td>{{flights.Arrival}}</td>
<td>{{flights.Duration}}</td>
<td>{{flights.Price}}</td>
</tr>
</tbody>
</table>
</body>
</html>
JavaScript 代码
var response;
var app = angular.module('mymodule', []);
app.controller('myCtrl', function($scope, $http)
{ $http.get("Flights.php")
.success(function(response)
{
//$scope.myWelcome = response;
//$scope.myWelcome = response.data;
$scope.response = response.data;
console.log(response);
})
.error(function()
{
$scope.response = "error in fetching data";
});
});
PHP 代码
<?php
$conn = mysqli_connect("localhost","","",'flight_details');
$data = array();
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
else
{
$sql = "select * from flights";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while ($row = $result->fetch_array())
{
$data[] = $row;
}
$res_final = json_encode($data);
echo $res_final;
}
else
{
echo"0 results";
}
$conn->close();
}
?>
此外,当我看到控制台时,我可以找到对象(数组元素)作为 Array[6]0: Object1: Object2: Object3: Object4: Object5: Objectlength: 6__proto__: Array[0] 通过这个我知道数据已经传递给 javascript 但是 Angularjs 代码/javascript 代码是不合适的。 所以,请帮我解决这个问题,在此先感谢
最佳答案
你应该这样做:
$scope.response = response;
代替:
$scope.response = response.data;
原因如下:
如果你使用 promise :
.then(function successCallback(response)
那么你应该做 response.data
;
当您使用 .success
时,第一个参数已经是您的 response.data
。
在这种情况下,您将其称为“响应”,这可能让您感到困惑。使用 .success 时避免将参数命名为“响应”。使用类似的东西:
.success(function(data) {
$scope.lstWeeklyMenu = data;
看看:http://www.codelord.net/2015/05/25/dont-use-$https-success/
和
https://www.peterbe.com/plog/promises-with- $http
简而言之:
.then(response)
你得到响应对象:
响应对象具有这些属性:
- data – {string|Object} – 使用转换函数转换的响应主体。
- status – {number} – 响应的 HTTP 状态代码。
- headers – {function([headerName])} Header getter 函数。
- config – {Object} – 用于生成请求的配置对象。
- statusText – {string} – 响应的 HTTP 状态文本。
https://docs.angularjs.org/api/ng/service/ $http
并使用 .success()
每个响应属性都是一个参数:
.成功(数据,状态)
关于javascript - 使用 AngularJs 和 PHP 显示从 MYSQL 收集的数据到 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40582406/