Home >Web Front-end >JS Tutorial >How to Submit URL-Encoded Form Data with AngularJS's $http Without jQuery?
In AngularJS, making AJAX requests with $http is a commonly addressed task. However, submitting url-encoded form data without relying on jQuery can be a challenge for beginners.
Failed Approaches
The mentioned approaches, such as using data: {username: $scope.userName, password: $scope.password} or params: {username: $scope.userName, password: $scope.password}, will not properly encode the data in url format.
Correct Solution
To achieve the desired functionality, Angular's $http service offers a transformRequest function that allows custom data transformation before sending it to the server.
$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 () {});
Enhanced Solution (AngularJS V1.4 and Later)
AngularJS versions 1.4 and later have introduced new services specifically designed for URL encoding parameters. Using these services, the process can be simplified further:
$http({ method: 'POST', url: url, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: angular.identity, params: {username: $scope.userName, password: $scope.password} }).then(function () {});
The above is the detailed content of How to Submit URL-Encoded Form Data with AngularJS's $http Without jQuery?. For more information, please follow other related articles on the PHP Chinese website!