質問

I am using AngularJS. I would like to send multiple data in a HTTP post through AngularJS. The backend runs Cakephp and I have verified that the Rest API works through python HTTP-post.

I have this controller that looks something like this;

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

When I run the code, the page fails to load AngularJS properly. If I comment away $http.post(post_url, post_data);, the code runs normally. Where did I go wrong?

Thank you very much.

役に立ちましたか?

解決

Two things here:

First, responses to $http requests are handled via Promises in AngularJS. If you are planning to do something with the response returned by the server, you should try adding Promise handling to your code. From the official AngularJS docs (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.
  });

Second, you could try encapsulating your $http call within a function, and then call that function on an event, once the entire AngularJS for the page is loaded.

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
        });    
    }
}])
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top