在 AngularJS 中如果要使用 AJAX 就必须使用 $http
基本用法
<!DOCTYPE HTML>
<html ng-app="BallApp">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<script src="module.js"></script>
</head>
<body>
<h2>View Render</h2>
<!-- 點擊後送出 request -->
<form ng-controller="AjaxCtrl">
<button ng-click="ajax()">AJAX</button>
</form>
</body>
</html>
$http.post
$http 也提供了快速使用 HTTP Verbs,例如直接使用 POST
注意:由于 AngularJS 的 POST 预设用的 Content-Type 是 application/json;charset=utf-8,而且也不会对资料做serialize的处理,如果直接使用后端会抓不到 POST 的内容
$http.post的使用方法很简单
$http.post('test.php', param).success(function(data) {});
在沒有任何修改狀況下,PHP 必須要用 input 取得資料
$value = json_decode(file_get_contents('php://input'));
print_r($value);
当然也可以利用 jQuery 的 $.post
var ballApp = angular.module('BallApp', [], function($httpProvider) {
// 利用 $httpProvider 修改 header
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
ballApp.controller('AjaxCtrl', function($scope, $http) {
$scope.ajax = function() {
// 利用 jQuery 的 $.param 將參數物件轉換成 query string
var data = $.param({name: 'Febr'});
$http.post('test.php', data)
.success(function(data) {
console.log(data);
});
};
});
又或者自己处理Serialize
var ballApp = angular.module('BallApp', [], function($httpProvider) {
// 修改 header
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
// Serialize function
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;
}
// 覆寫 $http 參數處理的方法(利用param function 處理參數)
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});
ballApp.controller('AjaxCtrl', function($scope, $http) {
$scope.ajax = function() {
$http.post('test.php', {name: 'Febr'})
.success(function(data) {
console.log(data);
});
};
});