How do I POST urlencoded form data with $http without jQuery?

后端 未结 11 2375
生来不讨喜
生来不讨喜 2020-11-21 23:27

I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.

I am trying to make an AJAX call to the server side, using

相关标签:
11条回答
  • 2020-11-22 00:05

    From the $http docs this should work..

      $http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
        .success(function(response) {
             // your code...
         });
    
    0 讨论(0)
  • 2020-11-22 00:06

    Though a late answer, I found angular UrlSearchParams worked very well for me, it takes care of the encoding of parameters as well.

    let params = new URLSearchParams();
    params.set("abc", "def");
    
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
    let options = new RequestOptions({ headers: headers, withCredentials: true });
    this.http
    .post(UrlUtil.getOptionSubmitUrl(parentSubcatId), params, options)
    .catch();
    
    0 讨论(0)
  • 2020-11-22 00:07

    I think you need to do is to transform your data from object not to JSON string, but to url params.

    From Ben Nadel's 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".

    Example from here.

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

    UPDATE

    To use new services added with AngularJS V1.4, see

    • URL-encoding variables using only AngularJS services
    0 讨论(0)
  • 2020-11-22 00:12

    URL-encoding variables using only AngularJS services

    With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:

    1. $httpParamSerializerJQLike - a serializer inspired by jQuery's .param() (recommended)

    2. $httpParamSerializer - a serializer used by Angular itself for GET requests

    Example usage

    $http({
      url: 'some/api/endpoint',
      method: 'POST',
      data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
      }
    }).then(function(response) { /* do something here */ });
    

    See a more verbose Plunker demo


    How are $httpParamSerializerJQLike and $httpParamSerializer different

    In general, it seems $httpParamSerializer uses less "traditional" url-encoding format than $httpParamSerializerJQLike when it comes to complex data structures.

    For example (ignoring percent encoding of brackets):

    Encoding an array

    {sites:['google', 'Facebook']} // Object with array property
    
    sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike
    
    sites=google&sites=facebook // Result with $httpParamSerializer
    

    Encoding an object

    {address: {city: 'LA', country: 'USA'}} // Object with object property
    
    address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike
    
    address={"city": "LA", country: "USA"} // Result with $httpParamSerializer
    
    0 讨论(0)
  • 2020-11-22 00:14

    If it is a form try changing the header to:

    headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
    

    and if it is not a form and a simple json then try this header:

    headers[ "Content-type" ] = "application/json";
    
    0 讨论(0)
  • 2020-11-22 00:21

    The problem is the JSON string format, You can use a simple URL string in data:

    $http({
        method: 'POST',
        url: url,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        data: 'username='+$scope.userName+'&password='+$scope.password
    }).success(function () {});
    
    0 讨论(0)
提交回复
热议问题