【问题标题】:AngularJs $http post successCallback is causing the page to redirect even when the server responds with a 200 status即使服务器以 200 状态响应,AngularJs $http post successCallback 也会导致页面重定向
【发布时间】:2016-03-14 15:27:12
【问题描述】:

我在 agularjs 中编写了一个简单的控制器来处理表单提交。使用 ng-submit 提交表单。

服务器正在成功处理 post 请求并返回 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);
        });
    };
}]);

【问题讨论】:

  • 你能展示你的表单元素吗?
  • 请粘贴您的表单代码。

标签: javascript angularjs


【解决方案1】:

发生这种情况通常是因为您没有阻止表单的默认操作,因此在发送 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 属性,则表单提交将被angular 自动阻止。您没有显示相关的 HTML 表单,因此我们不知道这是否适用于您的情况。

【讨论】:

    【解决方案2】:

    尝试这样改变

    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);
                });
            };
        }]);
    

    感谢和欢呼

    【讨论】:

    • 为什么这样可以解决问题?好的答案通常应该包含一些关于更改内容和原因的解释,而不仅仅是代码。
    【解决方案3】:

    看来这个问题并没有看起来那么难解决。

    我从表单元素中删除了 action="" 属性,它开始按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 2019-04-02
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2021-12-26
      相关资源
      最近更新 更多