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

How to POST URL-Encoded Form Data with AngularJS's $http Service?

Linda Hamilton
Release: 2024-12-11 05:16:11
Original
964 people have browsed it

How to POST URL-Encoded Form Data with AngularJS's $http Service?

POSTing URL-Encoded Form Data with $http in AngularJS

Understanding the Issue

As a new AngularJS user, you encountered challenges while sending data to the server using the $http service. Specifically, you faced issues when attempting to send data in the URL-encoded format.

The Solution

To resolve this problem, you need to convert your data to URL parameters instead of JSON strings. Ben Nadel explains this in his blog:

By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content-type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".
Copy after login

Example

Here's an example that demonstrates how to post URL-encoded form data using $http:

$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

Update for AngularJS v1.4 and Later

For AngularJS v1.4 and later, you can leverage the new services available to achieve the same result:

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: $httpParamSerializer
});
Copy after login

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