如何使用JQuery Ajax AngularJs进行post-req



我正在尝试发布请求代码-

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">

我创建了五个与上面类似的字段(名字、姓氏、电子邮件、电话、回复(,这些都是我的输入字段。

在提出请求时,我得到了502状态代码。

当我向邮差提出要求时,一切都很顺利。。。我的api正在接受JSON。从邮递员那里我把尸体当作json

邮差传递的尸体-

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

我是AngularJs Ajax和JQuery的新手,我一定在代码中犯了一些错误,请帮我解决这个问题。

我不确定502错误,但如果这个建议有帮助,为什么要使用带有angular的jQuery?有点违背目的。它们可以一起使用,但实际上没有意义。它们以完全不同的方式做事,angular为您可能希望JQ做的一切提供了解决方案,例如ajax调用。这是你的相同代码,角度化(如果你决定最小化你的脚本,包括注入保护(

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

最新更新