$http.post在AngularJS中不起作用。

14 浏览
0 Comments

$http.post在AngularJS中不起作用。

当我使用$http.get时,我的代码可以工作,但是如果我使用$http.post,则无法将参数发送到请求的.php文件中。\n这是Service函数:\n

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

\n和Controller函数:\n

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

\n和我的AJAXRequest.php文件:\n


\n如果我使用$http.post()\n输出:\n

 array (size=0)
  empty

\n如果我使用$http.get()\n输出结果如下:\n

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

\n我在FireBug工具中检查了post请求,它确实将数据发送到我的php文件中,但php文件没有接收到任何参数。\n如果我使用$.ajax$.post,我的代码可以工作并得到响应。

0
0 Comments

问题出现的原因:使用AngularJS的$http.post方法发送POST请求时,无法成功发送数据到服务器端的PHP文件,而且PHP文件返回的是空消息。但是,如果使用jQuery的$.post方法发送POST请求,则可以成功发送数据。

解决方法:将发送POST请求的数据以对象的形式传递给$http.post方法。

文章内容如下:

在AngularJS中使用$http.post方法发送POST请求时,有用户遇到了问题。用户在代码中使用了如下方式来发送POST请求:

$http.post('/data/AJAXRequest.php', { mydata: 1, abcd: 2 })

然而,用户发现该方法并未能成功发送数据到服务器端的PHP文件,而且PHP文件返回的是空消息。值得注意的是,用户尝试使用jQuery的$.post方法来发送POST请求时,却能够成功发送数据。

针对这个问题,我们提供了解决方法:将发送POST请求的数据以对象的形式传递给$http.post方法。修改后的代码如下:

$http.post('/data/AJAXRequest.php', { mydata: 1, abcd: 2 })

通过以上的修改,用户可以成功地发送POST请求并获取到服务器端返回的数据。

希望以上的解决方法能够帮助到遇到类似问题的用户。

0
0 Comments

在使用AngularJS的$http.post方法时,我遇到了一个问题。但是我发现问题并不在于Angular的http post方法,而是在于我尝试获取post数据的地方。

$params = json_decode(file_get_contents('php://input'),true);

我使用了这段代码来从Angular获取post数据,并且它完美地起作用了。

0
0 Comments

问题出现的原因是AngularJS默认将数据发送为application/json格式,而PHP默认解析的是application/x-www-form-urlencoded格式。解决方法是在发送请求时设置Content-Type头部为application/x-www-form-urlencoded,或者在PHP文件中设置JSON头部。

具体的解决方法如下:

$http({
    method: 'POST',
    url: '/data/AJAXRequest.php',
    data: 'mydata=1&abcd=2',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(....);

这样就可以成功发送数据了。

补充说明,mydata=1&abcd=2是序列化的数据。你可以让AngularJS 1.4自动为你完成序列化,或者使用一个转换请求函数来处理。我发现后者更简单,这样你就可以像使用jQuery一样使用JSON数据。

0