当前位置:Gxlcms > JavaScript > AngularJS Ajax详解及示例代码

AngularJS Ajax详解及示例代码

时间:2021-07-01 10:21:17 帮助过:5人阅读

AngularJS提供$http控制,可以作为一项服务从服务器读取数据。服务器可以使一个数据库调用来获取记录。 AngularJS需要JSON格式的数据。一旦数据准备好,$http可以用以下面的方式从服务器得到数据。

  1. function studentController($scope,$http) {
  2. var url="data.txt";
  3. $http.get(url).success( function(response) {
  4. $scope.students = response;
  5. });
  6. }

在这里,data.txt中包含的学生记录。 $http服务使Ajax调用和设置针对其学生的属性。 “学生”模型可以用来用来绘制 HTML 表格。

例子

data.txt

  1. [
  2. {
  3. "Name" : "Mahesh Parashar",
  4. "RollNo" : 101,
  5. "Percentage" : "80%"
  6. },
  7. {
  8. "Name" : "Dinkar Kad",
  9. "RollNo" : 201,
  10. "Percentage" : "70%"
  11. },
  12. {
  13. "Name" : "Robert",
  14. "RollNo" : 191,
  15. "Percentage" : "75%"
  16. },
  17. {
  18. "Name" : "Julian Joe",
  19. "RollNo" : 111,
  20. "Percentage" : "77%"
  21. }
  22. ]

testAngularJS.html

  1. <html>
  2. <head>
  3. <title>Angular JS Includes</title>
  4. <style>
  5. table, th , td {
  6. border: 1px solid grey;
  7. border-collapse: collapse;
  8. padding: 5px;
  9. }
  10. table tr:nth-child(odd) {
  11. background-color: #f2f2f2;
  12. }
  13. table tr:nth-child(even) {
  14. background-color: #ffffff;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <h2>AngularJS Sample Application</h2>
  20. <div ng-app="" ng-controller="studentController">
  21. <table>
  22. <tr>
  23. <th>Name</th>
  24. <th>Roll No</th>
  25. <th>Percentage</th>
  26. </tr>
  27. <tr ng-repeat="student in students">
  28. <td>{{ student.Name }}</td>
  29. <td>{{ student.RollNo }}</td>
  30. <td>{{ student.Percentage }}</td>
  31. </tr>
  32. </table>
  33. </div>
  34. <script>
  35. function studentController($scope,$http) {
  36. var url="data.txt";
  37. $http.get(url).success( function(response) {
  38. $scope.students = response;
  39. });
  40. }
  41. </script>
  42. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
  43. </body>
  44. </html>

输出

要运行这个例子,需要部署textAngularJS.html,data.txt到一个网络服务器。使用URL在Web浏览器中打开textAngularJS.html请求服务器。看到结果如下:

以上就是AngularJS Ajax的基础资料整理,后续继续整理相关资料,谢谢大家对本站的支持!

人气教程排行