如何使用jquery ajax angularjs生成post请求

7cwmlq89  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(308)

我正在尝试创建一个post请求代码-

var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.data = {};
            $scope.reqCalling = function () {
                let settings = {
                    "async": true,
                    "crossDomain": true,
                    "url": "myUrl",
                    "method": "POST",
                    "headers": {
                        "content-type": "application/json",
                    },
                    "data": JSON.stringify($scope.data),
                }
                $.ajax(settings).done(function (response) {
                    console.log("Success",response);
                    $scope.data = {};
                    $scope.$apply()
                    return false;
                }).fail(function (error) {
                    console.log("Failed",error);
                    // location.reload();
                });
            }
        });

输入一个字段的代码

<input type="email" class="form-control" maxlength="255" placeholder="Email..." ng-model="data.email" name="email">

我已经创建了五个类似上面的字段(firstname、lastname、email、phone、response),这些是我的输入字段。
在提出请求时,我得到502状态代码。
当我向 Postman 提出请求时,一切正常。。。我的api正在接受json。从 Postman 那里,我把尸体作为json传递过来
Postman 送来的尸体-

{
        "firstname" : "firstname",
        "lastname" : "lastname",
        "phone" : "0000000000",
        "email" : "abc@pqr.com",
        "response" : "Testing"
    }

我是angularjs ajax和jquery新手,我一定是在代码中犯了一些错误,请帮我解决这个问题。

mm9b1k5b

mm9b1k5b1#

我不确定502错误,但如果这个建议有帮助,为什么要将jquery与angular一起使用呢?有点达不到目的。它们可以一起使用,但没有什么意义。他们以完全不同的方式做事情,angular为您可能希望jq做的任何事情提供了解决方案,例如ajax调用。这是相同的代码,Angular 化(如果您决定最小化脚本,则包括注入保护)

var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', '$http', function($scope, $http) {
  $scope.data = {};
  $scope.reqCalling = function() {
    let settings = {
      "url": "myUrl",
      "method": "post",
      "headers": {
        "content-type": "application/json",
      },
      "data": $scope.data // you don't have to stringify the post vars
    }
    $http(settings).then(
      // success!
      function(response) {
        // success data: response.data
      },
      // error
      function(response) {
        if (!angular.isObject(response.data) ||
          !response.data.message) {
          // error: unknown error
        } else {
          // error : response.data.message
        }
      }

    )
  }
}]);

相关问题