$ http.post在AngularJS中不起作用
当我使用$http.get
我的代码工作,但如果我使用$ http.post,我永远不会得到请求.php文件的参数。
这是服务function:
TestPanel.service('MySampleService', function ($http, $q) { this.getAllPosts = function () { var def = $q.defer(); $http.post('/data/AJAXRequest.php', 'mydata=1&abcd=2').success(function (data) { if (data == null) def.reject('ERROR: DATA IS NULL'); else if (data.HasError) def.reject('ERROR: ' + data.Message); else def.resolve(data); }).error(function () { def.reject('ERROR: Sorry, unable to complete your request.'); }); return def.promise; } });
和控制器function:
TestController.controller('PostCtrl', ['$scope', '$http', 'MySampleService', function ($scope, $http, MySampleService) { function FetchPostsList() { MySampleService.getAllPosts().then(function (data) { $scope.lstPosts = data.ResponseData; $scope.totalRecords = data.totalRecords; console.info('DATA=' + $scope.lstPosts); }, function (err) { console.info('err=' + err); }); } FetchPostsList(); } ]);
和我的AJAXRequest.php文件
如果我使用$ http.post()
输出 :
array (size=0) empty
如果我使用$ http.get() 我的输出是:
array (size=2) 'mydata' => string '1' (length=1) 'abcd' => string '2' (length=1)
我检查了FireBug工具中的post,它将数据发送到我的php文件。 但php文件没有params。
如果我使用$ .ajax或$ .post我的代码工作,它会给出响应。
如果在标题中指定内容类型,该怎么做,具体如下:
$http({ method: 'POST', url: '/data/AJAXRequest.php', data: { mydata: 1, abcd: 2 }, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(....);
从这个问题中发现了与PHP有关的评论: AngularJs $ http.post()不发送数据
似乎Angular默认发送为application / json,这可能会混淆PHP。
我遇到了同样的问题,但我发现在角度http post方法中没有问题,问题是我在哪里试图获取发布数据。
$params = json_decode(file_get_contents('php://input'),true);
我使用此代码从角度获取发布的数据,其工作就像一个魅力
发布这样的数据:
$http.post('/data/AJAXRequest.php', { mydata: 1, abcd: 2 })
$http({ method: 'POST', url: 'http://mtapi.azurewebsites.net/api/sectiontype', dataType: 'json', data: {SectionTypeId:0, Name: $scope.message}, headers: { 'Content-Type': 'application/json; charset=UTF-8' } }).success(function (data) { alert(data); }).error(function (data) { alert(data); });
必须在数组的末尾添加标头,否则它将无法工作。