POSTing URL-Encoded Data with $http without jQuery
As an AngularJS newbie, you're seeking a way to make AJAX requests without relying on jQuery. While your initial approach with $.param worked, you'd like to eliminate the jQuery dependency.
Your subsequent attempts with data and params failed to yield desired results, and JSON stringification proved unsuccessful as well. AngularJS certainly offers a method for this, so let's explore the solution.
Transforming Data for URL Parameters
The key to sending form data via POST is to transform your object data into URL parameters. AngularJS provides a transformRequest function that allows you to customize the request body before sending it.
Example Post Request with Transformation
$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 () {});
In this example:
AngularJS 1.4 and Beyond
With AngularJS 1.4 and later, new services have been introduced to further simplify this process. However, the above approach remains a valid solution for earlier versions.
The above is the detailed content of How to POST URL-Encoded Data in AngularJS without jQuery?. For more information, please follow other related articles on the PHP Chinese website!