AngularJS中使用Ajax
时间:2021-11-23 作者:匿名
AngularJS提供$http控制工作作为服务从服务器读取数据。 数据库服务器进行调用所需的记录。 AngularJS需要JSON格式的数据。 一旦准备好数据,$http可以用来获取来自服务器的数据以下列方式−
function studentController($scope,$https:) { var url = "data.txt"; $https:.get(url).success( function(response) { $scope.students = response; }); }
在这里,文件数据。 txt包含学生记录。 $http服务使得房地产一个ajax调用和设置响应的学生。 学生模型可以用来画在HTML表。
例子
data.txt
[ { "Name" : "Mahesh Parashar", "RollNo" : 101, "Percentage" : "80%" }, { "Name" : "Dinkar Kad", "RollNo" : 201, "Percentage" : "70%" }, { "Name" : "Robert", "RollNo" : 191, "Percentage" : "75%" }, { "Name" : "Julian Joe", "RollNo" : 111, "Percentage" : "77%" } ]
testAngularJS.htm
<html> <head> <title>Angular JS Includes</title> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "" ng-controller = "studentController"> <table> <tr> <th>Name</th> <th>Roll No</th> <th>Percentage</th> </tr> <tr ng-repeat = "student in students"> <td>{{ student.Name }}</td> <td>{{ student.RollNo }}</td> <td>{{ student.Percentage }}</td> </tr> </table> </div> <script> function studentController($scope,$http) { var url = "/data.txt"; $http.get(url).then( function(response) { $scope.students = response.data; }); } //请注意,1.2.15版本有效,更高版本写法有所不同,请查看最新文档说明 </script> <script src = "https://www.yangzhiw.cn/static/js/angularjs-1.2.15/angular.min.js"> </script> </body> </html>
输出
执行这个例子中,您需要部署testAngularJS.htm和data.txt文件到web服务器。 打开文件testAngularJS.htm在web浏览器中使用您的服务器的URL并看到结果。