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

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

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

  1. var app = angular.module('myApp', []);
  2. app.controller('myCtrl', function ($scope) {
  3. $scope.data = {};
  4. $scope.reqCalling = function () {
  5. let settings = {
  6. "async": true,
  7. "crossDomain": true,
  8. "url": "myUrl",
  9. "method": "POST",
  10. "headers": {
  11. "content-type": "application/json",
  12. },
  13. "data": JSON.stringify($scope.data),
  14. }
  15. $.ajax(settings).done(function (response) {
  16. console.log("Success",response);
  17. $scope.data = {};
  18. $scope.$apply()
  19. return false;
  20. }).fail(function (error) {
  21. console.log("Failed",error);
  22. // location.reload();
  23. });
  24. }
  25. });

输入一个字段的代码

  1. <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 送来的尸体-

  1. {
  2. "firstname" : "firstname",
  3. "lastname" : "lastname",
  4. "phone" : "0000000000",
  5. "email" : "abc@pqr.com",
  6. "response" : "Testing"
  7. }

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

mm9b1k5b

mm9b1k5b1#

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

  1. var app = angular.module('myApp', []);
  2. app.controller('myCtrl', ['$scope', '$http', function($scope, $http) {
  3. $scope.data = {};
  4. $scope.reqCalling = function() {
  5. let settings = {
  6. "url": "myUrl",
  7. "method": "post",
  8. "headers": {
  9. "content-type": "application/json",
  10. },
  11. "data": $scope.data // you don't have to stringify the post vars
  12. }
  13. $http(settings).then(
  14. // success!
  15. function(response) {
  16. // success data: response.data
  17. },
  18. // error
  19. function(response) {
  20. if (!angular.isObject(response.data) ||
  21. !response.data.message) {
  22. // error: unknown error
  23. } else {
  24. // error : response.data.message
  25. }
  26. }
  27. )
  28. }
  29. }]);
展开查看全部

相关问题