(1)作用
发送异步请求到服务端,动态获取数据
(2)最基本入门
1.创建一个列表,用来循环输出数据
<div ng-controller="myAppCtrl">
<ul>
<li ng-repeat="user in users">
{{user.name}}
</li>
</ul>
</div>
2.创建请求
<script type="text/javascript">
var myAppModule = angular.module("myApp",[]);
myAppModule.controller('myAppCtrl',['$scope','$http',function($scope,$http){
$http({
method:'GET',
url:'data.json'
}).success(function(data,status,headers,config){
console.log("success!...");
console.log(data);
$scope.users = data;
}).error(function(data,status,headers,config){
console.log("error!...");
});
}]);
</script>
3.创建返回的json数据
[{
"name":"test1"
},{
"name":"test2"
},{
"name":"test3"
}]
4.启动应用
(3)$http介绍
1.基本方法
1)语法格式
$http(config);
2)参数
名称 类型 细节
config object 描述了请求的相关信息,包含了以下的属性:
method – {string} – HTTP方法 (e.g. 'GET', 'POST', etc)
url – {string} – 请求的相对路径
params – {Object.<string|Object>} – 字符串构成的Map或者Object,后面会转化?key1=value1&key2=value2的形式加在url后面
data – {string|Object} – 存储在消息体中的数据,通常在发送post请求的时候使用
headers – {Object} – 代表了将要发送到服务端的Http消息头部
cache – {boolean|Cache} – 如果为true,则会对结果进行缓存If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.
timeout – {number|Promise} – 过期时间,单位为毫秒.
3)实例
$http({
url:'data.json',
method:'GET'
}).success(function(data,header,config,status){
//响应成功
}).error(function(data,header,config,status){
//处理响应失败
});
1.简便方法
1)get语法格式:
get(url, [config]) 简单示例:
$http.get('/someUrl').
success(function(data, status, headers, config) {
// 成功时候
}).
error(function(data, status, headers, config) {
// 失败时候
});
2)post
语法格式
post(url, data, [config]);
简单实例
post("/mypath", {name:'john',age:27});
本文介绍了AngularJS中$http服务的基础用法,包括发送异步请求到服务端、动态获取数据的方法。通过示例展示了如何配置请求参数及处理响应。
7654

被折叠的 条评论
为什么被折叠?



