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

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

    Here is the way it should be (and please no backend changes ... certainly not ... if your front stack does not support application/x-www-form-urlencoded, then throw it away ... hopefully AngularJS does !

    $http({
         method: 'POST',
         url: 'api_endpoint',
         headers: {'Content-Type': 'application/x-www-form-urlencoded'},
         data: 'username='+$scope.username+'&password='+$scope.password
     }).then(function(response) {
        // on success
     }, function(response) {
        // on error
     });
    

    Works like a charm with AngularJS 1.5

    People, let give u some advice:

    • use promises .then(success, error) when dealing with $http, forget about .sucess and .error callbacks (as they are being deprecated)

    • From the angularjs site here "You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go."

    If your data model is more complex that just a username and a password, you can still do that (as suggested above)

    $http({
         method: 'POST',
         url: 'api_endpoint',
         headers: {'Content-Type': 'application/x-www-form-urlencoded'},
         data: json_formatted_data,
         transformRequest: function(data, headers) {
              return transform_json_to_urlcoded(data); // iterate over fields and chain key=value separated with &, using encodeURIComponent javascript function
         }
    }).then(function(response) {
      // on succes
    }, function(response) {
      // on error
    });
    

    Document for the encodeURIComponent can be found here

提交回复
热议问题