使用AngularJS的POST表单数据

POST form data using AngularJS

本文关键字:表单 数据 POST AngularJS 使用      更新时间:2023-09-26

我正在尝试使用AngularJS将表单POST到我正在开发的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";

有什么想法吗?

试着像这样使用$http:

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