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

后端 未结 11 2578
生来不讨喜
生来不讨喜 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: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
    

提交回复
热议问题