AngularJS 专题
您的位置:JS框架 > AngularJS专题 > AngularJS Ajax
AngularJS Ajax
作者:--    发布时间:2019-11-20

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

function studentcontroller($scope,$http) {
var url="data.txt";
   $http.get(url).success( function(response) {
                           $scope.students = response; 
                        });
}

在这里,data.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.html
<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).success( function(response) {
                           $scope.students = response;
                        });
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

输出

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

angularjs httpreqest
 

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册