POSTing URL Encoded Form Data with $http in AngularJS
When working with AngularJS, developers often face the task of making AJAX calls to remote servers. To send parameters, various approaches have been explored.
One method involves using jQuery's $.param() function. However, to eliminate jQuery dependency, several other options have been considered, including passing data as an object, using params, and utilizing JSON.stringify.
The solution lies in transforming the outgoing request data from an object to URL parameters. AngularJS by default serializes data as JSON for posting. To post as a FORM post, the serialization algorithm must be changed and the content-type must be set to "application/x-www-form-urlencoded."
The following modified code demonstrates how to do this:
$http({ method: 'POST', url: url, 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("&"); }, data: {username: $scope.userName, password: $scope.password} }).then(function () {});
For further guidance, refer to Ben Nadel's blog or the example provided above.
The above is the detailed content of How to POST URL-Encoded Form Data Using $http in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!