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

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

Linda Hamilton
Release: 2024-12-03 17:12:14
Original
414 people have browsed it

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

POSTing URL-Encoded Form Data with $http without jQuery

When making AJAX calls using AngularJS' $http service, you may encounter challenges when sending form data that requires URL-encoding. This can be particularly frustrating for those seeking a jQuery-free solution.

Problem

Attempts to send form data using Angular's $http service with the following approaches have resulted in failures:

  • data: {username: $scope.userName, password: $scope.password}
  • params: {username: $scope.userName, password: $scope.password}
  • data: JSON.stringify({username: $scope.userName, password: $scope.password})

Solution

To successfully POST URL-encoded form data, you need to transform the data object into URL parameters. According to Ben Nadel, Angular by default serializes the outgoing data as JSON and posts it with "application/json" content-type.

To change this behavior and post form data, update the code as follows:

data: {username: $scope.userName, password: $scope.password}
Copy after login
transformRequest: function(obj) {
    var str = [];
    for(var p in obj)
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
},
Copy after login

This code converts the JavaScript object into a URL-encoded string, allowing for successful POSTing of form data without jQuery.

Enhanced Solution with Angular 1.4

For AngularJS v1.4 and later, utilizing the newly added services provides an even simpler solution:

data: {username: $scope.userName, password: $scope.password},
headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
}
Copy after login

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