AngularJS Ajax示例使用$http
时间:2020-02-23 14:29:32 来源:igfitidea点击:
在本教程中,我们将使用$HTTP服务调用Angular JS中的Ajax。
AngularJs提供开箱即用的多个服务。
$HTTP服务可用于执行HTTP请求。
它允许我们通过控制器构造函数注入它来创建任何HTTP请求。
在此示例中,我们将使用来自服务器的Ajax请求读取Countinioun.json,并将在表中显示它的数据。
a app.js中的ajax请求
var app = angular.module('myApp', []);
app.controller('theitroadContoller', function($scope,$http) {
var url = "countries.json";
$http.get(url).success( function(response) {
$scope.countries = response;
});
});
我们可以在此处看到,我们在此处注入Controller功能中的$HTTP并为国家/地区的响应分配。
项目结构:
第1步:在Eclipse中创建名为"Angularjsajaxexample"的动态Web项目。
第2步:我们将从服务器读取Counteries.json。
在WebContent文件夹中创建CoundientS.JSON,JSON文本下面。
[
{
"id": 1,
"countryName": "San Franceco",
"population": 10000
},
{
"id": 2,
"countryName": "Bhutan",
"population": 7000
},
{
"id": 3,
"countryName": "Nepal",
"population": 8000
},
{
"id": 4,
"countryName": "China",
"population": 20000
}
]
第3步:在WebContent文件夹中创建AngularJsajaxexample.html,如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Angular js</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" type="text/css" href="table.css">
</head>
<body>
<div ng-app="myApp" ng-controller="theitroadContoller">
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Country Name</th>
<th>Population</th>
</tr>
</thead>
<tr ng-repeat="con in countries">
<td> {{ con.id }}</td>
<td> {{ con.countryName }}</td>
<td >{{ con.population }}</td>
</tr>
</table>
</div>
</body>
</html>
其中我们正在使用ng-repeat标记来迭代姓名列表并在表中显示它。
第4步:在WebContent文件夹中创建App.js,如下所示:
var app = angular.module('myApp', []);
app.controller('theitroadContoller', function($scope,$http) {
var url = "countries.json";
$http.get(url).success( function(response) {
$scope.countries = response;
});
});
步骤5:我们将在此表上应用样式,因此在WebContent文件夹中创建表.CSS。
table {
font-family: "Helvetica Neue", Helvetica, sans-serif
}
caption {
text-align: left;
color: silver;
font-weight: bold;
text-transform: uppercase;
padding: 5px;
}
thead {
background: SteelBlue;
color: white;
}
th,
td {
padding: 5px 10px;
}
tbody tr:nth-child(even) {
background: WhiteSmoke;
}
tbody tr td:nth-child(2) {
text-align:center;
}
tbody tr td:nth-child(3),
tbody tr td:nth-child(4) {
text-align: right;
font-family: monospace;
}
tfoot {
background: SeaGreen;
color: white;
text-align: right;
}
tfoot tr th:last-child {
font-family: monospace;
}
步骤6:在服务器上运行HTML文件。
右键单击"angularjsajaxexample.html"并转到运行 - >在服务器上运行。
我们将看到以下输出:
URL:http://localhost:8080/AngularJSAjaxExample/angularJSAjaxExample.html

