Easiest way to transform request into FormData

2
this.getArray = function(callback){
    $http({
        method: "post",
        url: "index.php?modulo=ClientesOnline&acao=getClientes",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        data: $.param({ajax:1}),
    }).success(callback);
    //$http.post("index.php?modulo=ClientesOnline&acao=getClientes", {ajax:1}).success(callback);
};

Personally, the code above was made by me through various searches.

My question

There is some easier way to write this line:

headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 

Because 'application/x-www-form-urlencoded' is a little complicated to write on a day to day basis. :

Thank you in advance! Thanks.

    
asked by anonymous 23.08.2016 / 20:31

2 answers

0

You can store the headers in a variable:

var headersAjax = {'Content-Type': 'application/x-www-form-urlencoded'};

And so, whenever you want to make an Ajax request with this header, you use the contents of the variable:

this.getArray = function(callback) {
    $http({
        method: "post",
        url: "index.php?modulo=ClientesOnline&acao=getClientes",
        headers: headersAjax,
        data: $.param({ajax:1}),
    }).success(callback);
};
    
23.08.2016 / 22:21
0

You can use $ httpProvider which is a good place where you can define settings that are common to multiple requests. Using your case as an example, it could be done this way:

angular.module(<nomeDoModulo>).config(['$httpProvider', function($httpprovider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}]);

By doing so, all your POST requests will have their request header modified for the one we defined.

To learn more about this service, you have the link $ httpProvider

    
05.09.2016 / 04:27