使用AngularJS POST表单数据

时间:2014-09-16 14:59:38

标签: javascript angularjs forms rest post

我正在尝试使用AngularJS将表单发布到我正在开发的API。

表单包含novalidatename="addMatchForm"ng-submit="submit(addMatchForm)"addMatchForm如下:

app.controller('addMatchController', ['$scope', 'players', 'matches', function($scope, players, matches) {

    ...

    $scope.submit = function(form) {
        form.submitted = true;

        // Make sure we don't submit the form if it's invalid
        if ( form.$invalid ) return;

        matches.add(form).success(function(data) {
            console.log('post result:', data);
        })
    }
}]);

app.factory('matches', function($http) {
    return {
        add: function(data) {
            return $http.post('/matches', data);
        }
    }
});

但奇怪的是,每个输入的值在那时变成一个空对象。这是Chrome开发者工具的表单数据:

{"a_score":{},"b_score":{},"day":{},"month":{},"year":{},"a_player1":{},"a_player2":{},"b_player1":{},"b_player2":{},"submitted":true}:

我确实已经添加了content-type部分。

$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试像这样使用$ http:

return $http({
    method: 'POST',
    url: '/matches',
    data: $.param(data),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});