AngularJS Ajax

AngularJS提供了$http控件,该控件可作为从服务器读取数据的服务。服务器进行数据库调用以获取所需的记录。AngularJS需要JSON格式的数据。数据准备好后,可以使用$http通过以下方式从服务器获取数据-

functionstudentController($scope,$https:){varurl="data.txt";$https:.get(url).success(function(response){$scope.students=response;});}

这里,档案data.txt包含学生记录。$http服务发出一个ajax调用并设置对其属性students的响应。学生模型可以用来绘制HTML表格。

实例

data.txt

[{"Name":"SeaGull","RollNo":101,"Percentage":"80%"},{"Name":"DinkarKad","RollNo":201,"Percentage":"70%"},{"Name":"Robert","RollNo":191,"Percentage":"75%"},{"Name":"JulianJoe","RollNo":111,"Percentage":"77%"}]

testAngularJS.htm

<html><head><title>AngularJSIncludes</title><style>table,th,td{border:1pxsolidgrey;border-collapse:collapse;padding:5px;}tabletr:nth-child(odd){background-color:#f2f2f2;}tabletr:nth-child(even){background-color:#ffffff;}</style></head><body><h2>AngularJS-Ajax使用示例</h2><divng-app=""ng-controller="studentController"><table><tr><th>Name</th><th>RollNo</th><th>Percentage</th></tr><trng-repeat="studentinstudents"><td>{{student.Name}}</td><td>{{student.RollNo}}</td><td>{{student.Percentage}}</td></tr></table></div><script>functionstudentController($scope,$http){varurl="/run/angularjs/data.txt";$http.get(url).then(function(response){$scope.students=response.data;});}</script><scriptsrc="https://cdn.staticfile.org/angular.js/1.2.15/angular.min.js"></script></body></html>
测试看看‹/›

输出结果

图片.png

要执行此示例,您需要将testAngularJS.htmdata.txt文件部署到Web服务器。在网络浏览器中使用服务器的URL打开文件testAngularJS.htm,然后查看结果。

编辑于2024-05-23 20:37