这问题其实很简单。
以PHP为例:
angularjs的http请求默认请求下发送的是josn数据,所以PHP直接用$_POST请求是接收不到数据的,如下图:
后台返回数据为空:
我们要做的事情,就是把json数据,变成表单形式的数据,这样PHP可以直接通过$_POST进行取值,也就是我们平时用jquery的ajax发送请求时的数据格式,如下图:
这次后台有返回数据了:
我们要写的代码也很简单,其实就是改变一下请求头就行了。方法有两种:
一、
var ang = angular.module('myapp', []);
ang.config(function ($httpProvider) {
$httpProvider.defaults.transformRequest = function (data) { if (data === undefined) { return data; } return $.param(data); }; $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';});
第一种方法,最简单,方便实用。但是有时候我们引入一些别人的插件,用这种方法定义header会有报错,所以我们也可以用第二种方法。
二、
angular.module('myapp', [], function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
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;
};
$httpProvider.defaults.transformRequest = [function (data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
})
以上两种方法都可以,选一种亦可!