angularJs学习4:http请求

如何通过http从网络获取数据

1 读取json文件

AngularJS $http 是一个用于读取web服务器上数据的服务。
$http.get(url) 是用于读取服务器数据的函数。

以下是get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>

<div ng-app="myApp" ng-controller="customersCtrl">

<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.runoob.com/try/angularjs/data/Customers_JSON.php")
.success(function (response) {$scope.names = response.records;});
});
</script>

</body>
</html>

以下是post请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script>
function formController($scope, $http) {
$scope.commit = function() {
$http({
method:"POST",
url:"/liberty_oa_2015_4_21/login/login.do",
params:{
"userName":$scope.current.name,
"password":$scope.current.pass
}
}).success(function(data) {
console.log("success...");
}).error(function() {
alert("fail...");
});

};
};
</script>

表格显示

  1. 普通显示
    1
    2
    3
    4
    5
    6
    <table>
    <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
    </tr>
    </table>

2.带序号的显示

1
2
3
4
5
6
7
<table>
<tr ng-repeat="x in names">
<td>{{ $index + 1 }}</td>
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>