When making AJAX calls using AngularJS' $http service, you may encounter challenges when sending form data that requires URL-encoding. This can be particularly frustrating for those seeking a jQuery-free solution.
Attempts to send form data using Angular's $http service with the following approaches have resulted in failures:
To successfully POST URL-encoded form data, you need to transform the data object into URL parameters. According to Ben Nadel, Angular by default serializes the outgoing data as JSON and posts it with "application/json" content-type.
To change this behavior and post form data, update the code as follows:
data: {username: $scope.userName, password: $scope.password}
transformRequest: function(obj) { var str = []; for(var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); return str.join("&"); },
This code converts the JavaScript object into a URL-encoded string, allowing for successful POSTing of form data without jQuery.
For AngularJS v1.4 and later, utilizing the newly added services provides an even simpler solution:
data: {username: $scope.userName, password: $scope.password}, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
The above is the detailed content of How to POST URL-Encoded Form Data with AngularJS's $http Service Without jQuery?. For more information, please follow other related articles on the PHP Chinese website!