1

我正在使用 AngularJS。我想通过 AngularJS 在 HTTP 帖子中发送多个数据。后端运行 Cakephp,我已经验证了 Rest API 通过 python HTTP-post 工作。

我有一个看起来像这样的控制器;

angular.module('myApp.controllers', []).
    controller('AlertDemoCtrl', ['$http', function($http) 
    {
        var post_url;
        var post_data;

        post_url="http://127.0.0.1/api_XXX/";

        post_data = {'data[Table1][field1]':'XX',
                     'data[Table2][0][field1]':'AA', 
                     'data[Table2][0][field2]':'BB', 
                     'data[Table2][0][field3]':'CC'
                    };

        $http.post(post_url, post_data);    
    }])

当我运行代码时,页面无法正确加载 AngularJS。如果我注释掉$http.post(post_url, post_data);,代码会正常运行。我哪里做错了?

非常感谢。

4

1 回答 1

0

这里有两件事:

首先,对$http请求的响应是通过 AngularJS 中的 Promises 处理的。如果你打算对服务器返回的响应做一些事情,你应该尝试在你的代码中添加 Promise 处理。来自官方 AngularJS文档(v1.3.0)

// Simple POST request example (passing data) :
$http.post(post_url, post_data).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

其次,您可以尝试将您的$http调用封装在一个函数中,然后在加载页面的整个 AngularJS 后在事件上调用该函数。

angular.module('myApp.controllers', []).
controller('AlertDemoCtrl', ['$http', function($http) 
{
    var post_url;
    var post_data;

    post_url="http://127.0.0.1/api_XXX/";

    post_data = {'data[Table1][field1]':'XX',
                 'data[Table2][0][field1]':'AA', 
                 'data[Table2][0][field2]':'BB', 
                 'data[Table2][0][field3]':'CC'
                };

    $scope.fetch = function() {
        $http.post(post_url, post_data).success(function() {
            // handle response here
        }).error(function() {
            // handle error here
        });    
    }
}])
于 2015-10-25T07:38:04.820 回答