$http 服務(wù)是什么夕冲?
$http 就是JQuery中的$.ajax
如何用衣迷?
請(qǐng)求一個(gè)已存在的json文件
news.json
{
"status": "1",
"message": "成功",
"data": [
{
"id": "556",
"title": "left_top秘密任務(wù)",
"image": "/resources/news/1479110226.png",
"content": "",
"url": "/challenge",
"desc": "",
"created_at": "2016-06-27 11:25:29"
}, {
"id": "555",
"title": "right_top曬勛章",
"image": "/resources/news/1476350699.png",
"content": "",
"url": "/medal",
"desc": "",
"created_at": "2016-06-27 11:23:56"
}, {
"id": "554",
"title": "left_bottom邀請(qǐng)有禮",
"image": "/resources/news/1476181116.png",
"content": "",
"url": "/invest_timeline",
"desc": "",
"created_at": "2016-05-17 17:40:05"
}, {
"id": "496",
"title": "right_bottom新手教程",
"image": "/resources/news/1476181156.png",
"content": "",
"url": "http://mp.weixin.qq.com/s?__biz=MzA5ODI4MjM1NA==&mid=2649936983&idx=2&sn=ebdaaa65f2216ff223973d25329339f5",
"desc": "",
"created_at": "2016-03-17 10:33:01"
}
]
}
controller
//初始我們定義一個(gè) $scope.news 請(qǐng)求成功之后我們給這個(gè)變量重新賦值
appH5.controller("myTabCtrl",['$scope','$http',function($scope,$http){
$scope.news=[];
$http.get("mock/news.json")
.success(function(res){
console.log(res);
if(res.status==1){
$scope.news=res.data;
}else{
alert(res.message);
}
}).error(function(){
console.log("error");
}).then(function(data){
console.log(data);
});
});
$http服務(wù)會(huì)返回一個(gè) promise作儿;你可以定義success方法說(shuō)明請(qǐng)求成功之后執(zhí)行什么霎槐;同樣你也可以定義error方法說(shuō)明請(qǐng)求成功之后執(zhí)行什么咨堤。
請(qǐng)求get請(qǐng)求的接口
// 請(qǐng)求成功之后我們給 orders 這個(gè)變量重新賦值
appH5.controller("myTabCtrl",['$scope','$http',function($scope,$http){
$http.get("http://www.mxx.com/test.php?c=orders")
.success(function(res){
console.log(res);
if(res.status==1){
$scope.orders=res.data;
}else{
alert(res.message);
}
}).error(function(){
console.log("error");
});
});
請(qǐng)求post請(qǐng)求的接口
// 請(qǐng)求成功之后我們給 orders 這個(gè)變量賦值
appH5.controller("myTabCtrl",['$scope','$http',function($scope,$http){
$http({
method:'post',
url:'http://www.mxx.com/test.php?c=login',
data:$.param({name:"aaa",id:1,age:20}),
headers:{'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(req){
console.log(res);
if(res.status==1){
$scope.orders=res.data;
}else{
alert(res.message);
}
})
});
- $.param方法是jQuery的序列化方法埂伦,post的用法需要借助這個(gè)類(lèi)庫(kù)仔蝌;并且需要設(shè)置headers:{'Content-Type': 'application/x-www-form-urlencoded'}
用$http發(fā)送get請(qǐng)求
appH5.controller("myTabCtrl",['$scope','$http',function($scope,$http){
$http({
method: 'GET',
url: 'http://www.mxx.com/test.php',
params: { c: 'orders' },//params作為url的參數(shù)
}).success(function(req){
console.log(req);
});
});
//最后請(qǐng)求的url實(shí)際上是
//http://www.mxx.com/test.php?c=orders泛领;
//params定義的參數(shù)會(huì)被拼接在url后面
$http發(fā)送POST請(qǐng)求
appH5.controller("myTabCtrl",['$scope','$http',function($scope,$http){
$http({
method:'post',
url:'http://www.mxx.com/test.php?c=login',
data:$.param({name:"aaa",id:1,age:20}),
headers:{'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(req){
console.log(req);
});
});
如果你需要在請(qǐng)求完成得到返回?cái)?shù)據(jù)之后執(zhí)行某段操作的話,你可以用 then()方法讓代碼順序執(zhí)行
appH5.controller("myTabCtrl",['$scope','$http',function($scope,$http){
$http({
method:'post',
url:'http://www.mxx.com/test.php?c=login',
data:$.param({name:"aaa",id:1,age:20}),
headers:{'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(req){
console.log(req);
}).then(function(res){
console.log("我是得到返回?cái)?shù)據(jù)之后才會(huì)執(zhí)行的操作");
});
});
- 為什么post請(qǐng)求我要用 $.param敛惊?
我們來(lái)看一下我們不用$.param把data序列化渊鞋,我們?cè)谡{(diào)試工具中看到的傳遞到后臺(tái)的參數(shù)
當(dāng)我們使用 jQuery的 ajax 方法,我們看到的參數(shù)是
jQuery的 ajax 方法
- 解釋 看起來(lái)執(zhí)行請(qǐng)求的代碼是一樣的瞧挤,但是實(shí)際發(fā)送的時(shí)候明顯后者是鍵值對(duì)的方式锡宋,前者則不是;為什么會(huì)出現(xiàn)這種問(wèn)題呢特恬?因?yàn)閖Query在發(fā)送 data里面的數(shù)據(jù)之前會(huì)進(jìn)行數(shù)據(jù)的序列化(Content-Type:application/x-www-form-urlencoded)如
var data= {name:"aaa",id:1,age:20};
// jQuery在post數(shù)據(jù)之前會(huì)把data轉(zhuǎn)換成字符串:"name=aaa&id=1&age=20"
相反的 Angular不會(huì)執(zhí)行這一操作执俩,它,默認(rèn)傳遞的json字符串(Content-Type: application/json;)癌刽,后端在取前端傳遞的參數(shù)時(shí)不能用 $_REQUEST/$_POST(本人只會(huì)PHP役首,這里以php為例),而必須用
$params = json_decode(file_get_contents('php://input'),true);
這種方式來(lái)獲取前端的參數(shù)显拜。這就意味著你一旦你之前用jQuery寫(xiě)的項(xiàng)目要用Angular重構(gòu)衡奥,那么后端的接口就必須一個(gè)一個(gè)更改獲取參數(shù)的方式;
-
如果不用后端改讼油,有沒(méi)有解決方案杰赛?
方案1,其實(shí)我已經(jīng)寫(xiě)出來(lái)了矮台,就是用$.param函數(shù)來(lái)序列化之后再賦值給$http 的data屬性乏屯,不過(guò)你得為了這個(gè)引入jQuery這個(gè)類(lèi)庫(kù)。(當(dāng)然如果你想寫(xiě)的話瘦赫,你自己可以寫(xiě)一個(gè)序列化函數(shù))
$http({
method:'post',
url:'http://www.mxx.com/test.php?c=login',
data:$.param({name:"aaa",id:1,age:20}),
headers:{'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(req){
console.log(req);
})
- 方案2 修改Angular的$httpProvider的默認(rèn)配置辰晕,這是最初我進(jìn)我們公司之后用的方法
angular.module('MyModule', [], function($httpProvider) {
// 設(shè)置 Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
/**
* 序列化data
* @param {Object} obj
* @return {String}
*/
var param = function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for(name in obj) {
value = obj[name];
if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
return query.length ? query.substr(0, query.length - 1) : query;
};
// 重寫(xiě) $http 服務(wù)的 transformRequest 方法對(duì)用戶傳遞過(guò)來(lái)的數(shù)據(jù)進(jìn)行序列化處理
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});
注 這只是簡(jiǎn)單用法,細(xì)節(jié)我會(huì)稍后編輯确虱,比如為什么post必須用$.param含友;和設(shè)置 header