Home > Article > Web Front-end > AngularJS initiates $http.post request example sharing
This article mainly shares with you examples of AngularJS initiating $http.post requests. I hope it can help everyone.
The code is as follows:
$http({ method:'post', url:'post.php', data:{name:"aaa",id:1,age:20} }).success(function(req){ console.log(req); })
At this time you will find that the returned data cannot be received, and the result is null. This is because it needs to be converted into form data.
Solution:
Configure $httpProvider:
var myApp = angular.module('app',[]); myApp.config(function($httpProvider){ $httpProvider.defaults.transformRequest = function(obj){ var str = []; for(var p in obj){ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); } $httpProvider.defaults.headers.post = { 'Content-Type': 'application/x-www-form-urlencoded' } });
Or configure in post:
$http({ method:'post', url:'post.php', data:{name:"aaa",id:1,age:20}, headers:{'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: function(obj) { var str = []; for(var p in obj){ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); } }).success(function(req){ console.log(req); })
The code is as follows:
app.controller('sprintCtrl', function($scope, $http) { $http.get("http://localhost:8080/aosapp/pt/service?formid=pt_aosapp_service_sprintlist&teamid=1") .success(function (response) {console.log($scope.sprintlist=response);}); });
In fact, the biggest difference between angularjs and jquery js is that angularjs is your first Build a complete page in your mind, and then use variables or placeholders to represent data. When the data comes, just fill it in directly; jquery dynamically modifies dom elements, such as adding and modifying dom tags, etc. The design ideas are different.
Related recommendations:
Example detailed explanation of AngularJS encapsulation $http.post()
angularJS implements $http.post and $http. Detailed explanation of get request code
Comparative analysis of the difference between $http.post and jQuery.post in AngularJS_AngularJS
The above is the detailed content of AngularJS initiates $http.post request example sharing. For more information, please follow other related articles on the PHP Chinese website!