Home > Web Front-end > JS Tutorial > How to POST URL-Encoded Data in AngularJS without jQuery?

How to POST URL-Encoded Data in AngularJS without jQuery?

DDD
Release: 2024-12-04 03:20:11
Original
200 people have browsed it

How to POST URL-Encoded Data in AngularJS without jQuery?

POSTing URL-Encoded Data with $http without jQuery

As an AngularJS newbie, you're seeking a way to make AJAX requests without relying on jQuery. While your initial approach with $.param worked, you'd like to eliminate the jQuery dependency.

Your subsequent attempts with data and params failed to yield desired results, and JSON stringification proved unsuccessful as well. AngularJS certainly offers a method for this, so let's explore the solution.

Transforming Data for URL Parameters

The key to sending form data via POST is to transform your object data into URL parameters. AngularJS provides a transformRequest function that allows you to customize the request body before sending it.

Example Post Request with Transformation

$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

In this example:

  • The transformRequest function iterates over the provided object, encoding each key and value.
  • The encoded key-value pairs are then joined into a single string separated by ampersands (&).

AngularJS 1.4 and Beyond

With AngularJS 1.4 and later, new services have been introduced to further simplify this process. However, the above approach remains a valid solution for earlier versions.

The above is the detailed content of How to POST URL-Encoded Data in AngularJS 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template