AngularJS SQL详解示例
AngularJS SQL详解示例,在所有Web应用程序中,我们都需要在数据库中保存、更新、插入和提取数据。AngularJS是由Google开发的JavaScript MVC(Model-View-Controller框架)。它帮助开发人员构建结构良好、易于测试和维护的前端应用程序。
特性
- 特性(Concept)
- 模板(Template)
- 指令
- 模型(Model)
- 作用域(Scope)
- 表达式(Expressions)
- 编译器(Compiler)
- 过滤器(Filter)
- 数据绑定
- 控制器(Controller)
- 模块(Module)
- 服务(Service)
AngularJS对于显示数据库中的数据非常有帮助。使用PHP与MySQL交互并获取JSON格式的数据,通过下面的基本示例,让我们详细了解AngularJS SQL。
例子:
<html>
<style>
table,
th,
td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<body>
<div ng-app="empApp"
ng-controller="employeeCtrl">
<table>
<tr ng-repeat="output in names">
<td>{{ output.Name }}</td>
<td>{{ output.Country }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module("empApp", []);
app.controller(
"employeeCtrl", function ($scope, $http) {
$http.get(
"employee_mysql.php").then(function (response) {
$scope.names = response.data.records;
});
});
</script>
</body>
</html>
说明: 从ng-app 指令开始。初始化并编译 HTML 模板 ng-controller 用于在 HTML 元素中指定一个控制器。PHP 和 MySQL这里主要是输出JSON 格式
PHP 和 MySQL服务端代码 :
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$connection = new mysqli("myServer",
"<username>",
"<password>",
"<dbname>");
$result = $connection->query(
"SELECT EmployeeName, EmployeeCity,
EmployeeCountry FROM Employees");
$output = "";
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($output != "") {
$output = ", ";
}
$output .= '{"Name":"' . $rs["EmployeeName"] . '", ';
$output .= '"City":"' . $rs["EmployeeCity"] . '", ';
$output .= '"Country":"' .
$rs["EmployeeCountry"] . '"}';
}
$output = '{"records":[' . $output . ']}';
$connection->close();
echo $output;
?>
假设MySQL中Employees 表有6 条记录。PHP 代码以 JSON 格式从 MySQL 检索数据,然后 Angular JS 显示输出。
输出:
HTML 代码:
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!