we are still learning how angular js works, we have little problem, we are making a http
post request with angular
var app = angular.module('app',['ngMessages']);
app.controller('AppCntrl', function($scope, PostingService) {
$scope.submitData = function() {
var data = {
name: "abc",
email: "email@example.com"
};
PostingService.postData(data);
}
});
app.service('PostingService', ['$http',function($http) {
this.postData = function(data) {
$http.post(
'/url/to/post/request',
data
)
.then(function successCallback(response) {
alert(response); // alerts undefined ***********************
}, function errorCallback(response) {
alert(response); // alerts undefined ***********************
});
}
}]);
while /url/to/post/request
has output as header('Content-Type:application/json;');
and json response is like {"status":true,"message":"this is message"}
but alert shows undefined
I've made few changes but it shouldn't matter. This code seems to work. > Change the variable requestURI
var app = angular.module('app', []) app.controller('AppCtrl', function($scope, PostingService) { $scope.submitData = function() { var data = { name: 'abc', email: 'email@example.com' } PostingService.postData(data) } }) app.service('PostingService', ['$http', function($http) { var requestURI = '' this.postData = function(data) { $http.post(requestURI, data) .then(function(response) { alert(response) }, function(response) { alert(response) }) } }])
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> </head> <body ng-app="app"> <div ng-controller="AppCtrl"> <button ng-click="submitData()">Make POST Request</button> </div> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.