gpt4 book ai didi

javascript - $http.post 在 AngularJS 中不起作用

转载 作者:可可西里 更新时间:2023-11-01 12:34:13 26 4
gpt4 key购买 nike

当我使用 $http.get 时,我的代码可以工作,但如果我使用 $http.post,我永远不会获得请求 .php 文件的参数。

这是服务功能:

    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;
}
});

和 Controller 功能:

 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 文件

<?php 
var_dump($_POST)
?>

如果我使用$http.post()

输出:

 array (size=0)
empty

如果我使用$http.get()我的输出是:

array (size=2)
'mydata' => string '1' (length=1)
'abcd' => string '2' (length=1)

我检查了 FireBug 工具中的帖子,它向我的 php 文件发送数据。但是 php 文件没有参数。

如果我使用 $.ajax$.post 我的代码可以正常工作并给出响应。

最佳答案

如果您在 header 中指定内容类型,具体如下:

$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() does not send data

Angular 似乎默认发送为 application/json,这会使 PHP 感到困惑。

关于javascript - $http.post 在 AngularJS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23027721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com