Home > Web Front-end > JS Tutorial > How to POST URL-Encoded Form Data Using $http in AngularJS?

How to POST URL-Encoded Form Data Using $http in AngularJS?

Mary-Kate Olsen
Release: 2024-12-24 13:15:13
Original
815 people have browsed it

How to POST URL-Encoded Form Data Using $http in AngularJS?

POSTing URL Encoded Form Data with $http in AngularJS

When working with AngularJS, developers often face the task of making AJAX calls to remote servers. To send parameters, various approaches have been explored.

One method involves using jQuery's $.param() function. However, to eliminate jQuery dependency, several other options have been considered, including passing data as an object, using params, and utilizing JSON.stringify.

The solution lies in transforming the outgoing request data from an object to URL parameters. AngularJS by default serializes data as JSON for posting. To post as a FORM post, the serialization algorithm must be changed and the content-type must be set to "application/x-www-form-urlencoded."

The following modified code demonstrates how to do this:

$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

For further guidance, refer to Ben Nadel's blog or the example provided above.

The above is the detailed content of How to POST URL-Encoded Form Data Using $http in AngularJS?. 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