使用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>
如何将url
和data
分别作为表单操作和输入?我不想发送JSON,我希望服务器端看到这是一个常规的HTML表单提交。
答案 0 :(得分:4)
感谢@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;
}
);
}
}
答案 1 :(得分:3)
这是我完成此操作的方法,首先将表单数据绑定到模型,然后使用转换将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;
});
}
}