【问题标题】:POST form data using AngularJS使用 AngularJS 发布表单数据
【发布时间】:2025-12-30 14:55:11
【问题描述】:

我正在尝试使用 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";

有什么想法吗?

【问题讨论】:

  • 什么时候值变空了?
  • 我猜在post之后。当我在return $http.post(...); 之前执行console.log(data) 时,它仍然是对象。
  • 你能告诉我们你的 HTML 吗?

标签: javascript angularjs forms rest post


【解决方案1】:

尝试像这样使用 $http:

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

【讨论】:

  • 当我将$http 替换为您提供的$http 时,出现以下错误:`无法读取未定义的属性'$name'。关于这可能来自哪里的任何想法?可能是我还包括 jQuery 的事实吗?
  • @CasCornelissen 尝试点击错误。它应该跳到它发生的那一行。
  • 花了一些时间(我切换到未缩小的 angular.js),但它位于 function consoleLog(type) 的中间,确切地说是 return logFn.apply(console, args);
  • 看起来是$.params,当我使用data: data 时,我没有收到错误消息。不过,空对象的问题仍然存在:(
  • 好吧,我想通了。我传递了整个表单对象(包括$dirty$valid 等内容)。我在控制器中创建了一个新对象,其中包含所有字段,这些字段通过双向数据绑定进行更新。不过,我最终还是使用了您建议的 $http 方法!