Easiest way to turn a request into Formdata

Asked

Viewed 155 times

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);
};

Guys, the code above was done by me through various searches.

My doubt

Is there any easier way to write that line:

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

For 'application/x-www-form-urlencoded' is a little tricky to write in everyday life. :/

Thanks in advance! Thanks.

  • That’s right, there’s a way?

  • You can leave the text in a file or resource snippet of the IDE and put in the code in the very few times it is necessary.

2 answers

0

You can make use of the $httpProvider which is a good place where you can set settings that are common to various 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';
}]);

Doing so, all your requisitions POST will have your request header modified to the one we set.

To learn more about this service, you have the documentation https://docs.angularjs.org/api/ng/provider/$httpProvider

0


You can store headers in a variable:

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

And then, whenever you want to make a request with Ajax 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);
};
  • Perfect, I had not thought to do this because I was seeking that language itself could have an easier way of writing. But it is a great solution expensive! Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.