php - AngularJS控制器未在路由视图中显示数据库中的数据
问题描述
我是 AngularJS 的新手,我正试图让我的一个路由页面从 MySQL 数据库加载数据。在网上看了几个不同的教程后,我似乎做错了什么,无法弄清楚为什么它不起作用。
索引页:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<base href="/angtest/">
<title>AngularJS Test</title>
</head>
<body ng-app="myApp">
<p>
<a href="home">Home</a> - <a href="about">About</a> - <a href="items">Items</a>
<br>
Click on the links to go to new pages.
</p>
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.7/angular-route.js"></script>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(['$routeProvider','$locationProvider',
function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when("/", {
templateUrl : "home.html"
}).when("/home", {
redirectTo : "/"
}).when("/about", {
templateUrl : "about.html"
}).when("/items", {
templateUrl : "items.html",
controller : "usercontroller"
}).otherwise({
redirectTo : "/"
});
}]);
app.controller("usercontroller", function($scope, $http){
$http.get("select.php")
.then(function(data){
$scope.items = data;
});
});
</script>
</body>
</html>
当转到 /home、/about 或 /items 时,页面加载正确,但 /items 没有获取数据库信息。
标题和描述是我想显示的项目表中的列。
项目页面:
<h1>MySQL Database</h1>
<div ng-controller="usercontroller">
<table>
<tr>
<th>Item Name</th>
<th>Item Description</th>
</tr>
<tr ng-repeat="x in items">
<td>{{ x.title }}</td>
<td>{{ x.description }}</td>
</tr>
</table>
</div>
选择脚本:
<?php
$connect = mysqli_connect("localhost", "USERNAME", "PASSWORD", "DBNAME");
$output = array();
$query = "SELECT * FROM items";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$output[] = $row;
}
echo json_encode($output);
}
?>
在控制台窗口中,不显示任何错误。
更新
为了检查控制台窗口,我将控制器更改为:
app.controller("usercontroller", function($scope, $http){
$http.get("select.php")
.then(function(data){
console.log(data);
$scope.items = data;
});
});
日志显示:
解决方案
项目页面
<h1>MySQL Database</h1> <div> <table> <tr> <th>Item Name</th> <th>Item Description</th> </tr> <tr ng-repeat="x in items"> <td>{{ x.title }}</td> <td>{{ x.description }}</td> </tr> </table> </div>
推荐阅读
- bash - ECS/Fargate 容器定义命令参数
- excel - 在 Excel 2010 中寻找公式或 VBA 以输入今天的日期并将其冻结
- javascript - javascript中的乒乓球游戏碰撞
- php - 映射查询结果仅聚合在一个数字下
- mysql - 如何在mysql的内部连接中使用WHERE IN
- git - 防止 Git 推送覆盖目录
- spring-boot - 启动 Spring MVC 应用程序时出现 AbstractMethodError
- django - 限制对注册页面的访问。如何使其仅适用于未经身份验证的用户?
- tensorflow - 如何在keras中设置双输入?
- html - 根据活动/非活动状态更改切换按钮的颜色(Bootstrap4)