Home > Web Front-end > JS Tutorial > How to Submit URL-Encoded Form Data with AngularJS's $http Without jQuery?

How to Submit URL-Encoded Form Data with AngularJS's $http Without jQuery?

Mary-Kate Olsen
Release: 2024-12-17 14:25:10
Original
687 people have browsed it

How to Submit URL-Encoded Form Data with AngularJS's $http Without jQuery?

Submitting Url-Encoded Form Data with $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 () {});
Copy after login

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 () {});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template