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
Mary-Kate OlsenOriginal
2024-12-17 14:25:10686browse

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

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!

Statement:
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