繁体   English   中英

如何使用Angular提交简单的表单

[英]How to submit a straightforward form using Angular

使用angular,我想提交一个表单并存储响应。 我的代码看起来像这样:

<form ng-controller="myController" action="myAction" method="POST">
    <input type="text" name="name" />
    <input type="submit" ng-click="submit" />
</form>

<script>
    function myController($scope, $http) {
        $scope.submit = function() {
            $http.post(url, data).success(function(data) {
                $scope.result = data;
            });
        }
    }
</script>

如何将urldata分别作为表单操作和输入? 我不想发送JSON,我希望服务器端看到这是一个常规的HTML表单提交。

感谢@Vincent Ramdhanie指出我正确的方向。 这是我最终做的,使用了大量的jQuery:

function myController($scope, $http) {
    $('form').submit(function() {
        return false;
    }); 

    $scope.submit = function() {
        form = $('form');
        data = form.serialize();
        url = form.attr('action')

        $http.post(url, data, 
            { headers: 
                { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
            }).success(function(data) {
                $scope.result = data;
            }
        );
    }
}

这就是我完成此操作的方法,首先将表单数据绑定到模型,然后使用转换将JSON数据转换为常规的post参数。 这个解决方案依赖于jQuery param()函数:

 <form ng-controller="myController" method="POST">
    <input type="text" name="name" ng-model="name"/>
    <input type="submit" ng-click="submit" />
 </form>

 function myController($scope, $http) {

    $scope.name = "";

    /* Helper function to transform the form post to a regular post rather than JSON */
    var transform = function(data) {
       return $.param(data);
    }

    $scope.submit = function() {
        $http.post('myAction', $scope.name, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
            transformRequest: transform
        })
         .success(function (data) {
             $scope.result = data;
         });
    }




}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM