AngularJS中的简单请求 --- $http --- 一个类似jquery的$.ajax的对象,用于异步请求
语法:
$http({
url:url, //请求的url路径
method:method, //GET/DELETE/HEAD/JSONP/POST/PUT
params:params , //转为 ?param1=xx1¶m2=xx2的形式
data: data //包含了将被当做消息体发送给服务器的数据,通常在POST请求时使用
}
}).success(function(response, status, header, config, statusText){
//成功处理
}).error(function(data,header,config,status){
//错误处理
});
特别注意:
1.请求参数说明:
url:url, //请求的url路径
method:method, //GET/DELETE/HEAD/JSONP/POST/PUT
params:params , //转为 ?param1=xx1¶m2=xx2的形式
data: data //包含了将被当做消息体发送给服务器的数据,通常在POST请求时使用
2.响应参数说明:
response --- 响应体,即:要请求的数据
status --- HTTP状态码
header --- 头信息
config --- 用来生成原始请求的完整设置对象
statusText --- 相应的HTTP状态文本
3.缓存HTTP请求
默认情况下,$http服务不会对请求进行本地缓存。在发送单独请求时,可通过向$http请求传递一个布尔参数来启用缓存
eg:
$http.get({'/api/users.json',{cache:true}})
.success(function(data){ })
.error(function(data){ })
解析:
第一次发送请求时,$http服务会向 /api/users.json发送一个GET请求,
第二次发送同一个GET请求时,$http服务会从缓存中取回请求的结果,而不会真的发送一个HTTP GET请求
设置启动缓存后,AngularJS默认会使用 $cacheFactory,这个服务在AngularJS启动时自动创建
如果想要对AngularJS使用的缓存进行更多的自定义控制,可以向请求传入一个自定义的缓存实例代替true。
1.GET方式 --- params参数会转为 ?param1=xx1¶m2=xx2的形式
1.$http请求:
$http({
url:"/api/users.json",
method:'GET',
params:{
'username':'jay'
}
}
}).success(function (response, status, headers, config) {
/*response -- 成功返回的数据
status -- 状态码
headers -- 头信息
config -- 其他信息
*/
}).error(function (response) {
}
});
2.快捷请求:
$http.get(url, [config])
.success(function(data){})
.error(function(data){});
2.POST方式
$http({method : 'POST',params : { id:123}, data:{name:'john',age:27}, url : "/mypath"})
.success(function(response, status, headers, config){
//do anything what you want;
})
.error(function(response, status, headers, config){
//do anything what you want;
});
2.快捷方式:
$http.post(url, $scope.formData).success(function (response, status, headers, config) {
......
}).error(function (response) {
......
});
3.$http提交表单 --- 与Spring MVC交互, 使用这种方式
通用方式:
$http({
method: "POST",
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.formData)
}).success(function(result){
}).error(function(result){
});
快捷方式:
$http.post(url, $scope.formData)
.success(function(result){
})
.error(function(result){
});
eg:
var data = {
"server":$scope.server,
"time":$("#time").val(),
"day":day
}
$http({
method: "post",
url: ctx+'/player/lossPlayer/list.htm',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param(data)
}).success(function(result){
if(result.tip!=undefined){
//当前绑定的数据清空
$scope.players = [];
alert(result.tip);
}else{
console.log(result.json);
$scope.players = $.parseJSON($.parseJSON(result.json).players);
}
});
4.使用$http指定的方法发送HTTP请求:
get(url, [config]);
delete(url, [config]);
post(url, data, [config]);
put(url, data, [config]);
5.发送jsonp请求:
为了发送JSONP请求,url中必须包含JSON_CALLBACK参数, jsonp(url,config) 其中config是可选的
eg:
var promise=$http.jsonp("/api/users.json?callback=JSON_CALLBACK");
AngularJS中的$http深入分析
最新推荐文章于 2019-03-11 15:13:29 发布