我在agularjs中编写了一个简单的控制器来处理表单提交。表格使用ng-submit提交。
服务器正在成功处理发布请求并返回http状态200。 但是AngularJs使用POST方法再次调用当前页面url,这导致服务器返回MethodNotAllowedException(Laravel 5.2)页面。
这是控制器代码。
app.controller('adminAddController', ['$scope', '$http', 'Page', function($scope, $http, Page){
$scope.formData = {};
$scope.processForm = function($event) {
console.log($scope.formData);
$http({
method : "post",
url : 'http://localhost:8000/api/blogs',
data : $scope.formData,
})
.then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
}]);
答案 0 :(得分:2)
通常会发生这种情况,因为您没有阻止表单的默认操作,所以在发送Ajax调用之后,表单会正常提交,然后浏览器会被重定向或根据表单提交重新加载页面。
如果你添加:
$event.preventDefault();
给你的经纪人,应该照顾它。
app.controller('adminAddController', ['$scope', '$http', 'Page', function($scope, $http, Page){
$scope.formData = {};
$scope.processForm = function($event) {
// prevent default form submission
$event.preventDefault();
console.log($scope.formData);
$http({
method : "post",
url : 'http://localhost:8000/api/blogs',
data : $scope.formData,
})
.then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
}]);
另外,per the angular documentation,如果您的<form>
元素没有action
属性,则表单提交将自动被有角度阻止。您没有显示相关表单HTML,因此我们不知道这是否适用于您的情况。
答案 1 :(得分:0)
尝试更改:
app.controller('adminAddController', ['$scope', '$http', 'Page', function($scope, $http, Page){
$scope.formData = {};
$scope.processForm = function($event) {
console.log($scope.formData);
$http.post('api/blogs', {data:$scope.formData})
.then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
}]);
谢谢&amp;干杯强>
答案 2 :(得分:0)
所以似乎问题并不像看起来那么困难。
我从表单元素中删除了action =“”属性,它开始按预期工作。