当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngularJS Ajax详解及示例代码

AngularJS Ajax详解及示例代码

2018年05月11日  | 移动技术网IT编程  | 我要评论

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 ajax的基础资料整理,后续继续整理相关资料,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网