Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How serialize objects with angularjs

How can I serialize an object without using the $.param jquery?

I want the object below:

var user = {username: 'ronald.araujo', password: '123456',};

to have the following output:

username=ronald.araujo&password=123456

Any suggestions? Remembering that I would do this using Angularjs or pure Javascript.

EDIT:

I am using the verb "save" ($resource) the angularjs. How could I set the header "application / x-www-form-urlencoded" and serialize?

like image 937
Ronald Araújo Avatar asked Mar 16 '23 14:03

Ronald Araújo


2 Answers

Pure javascript can do it just fine:

function serializeObj(obj) {
    var result = [];

    for (var property in obj)
        result.push(encodeURIComponent(property) + "=" + encodeURIComponent(obj[property]));

    return result.join("&");
}

var user = {
    username: 'ronald.araujo',
    password: '123456'
};

var serialized = serializeObj(user);
console.log(serialized); //username=ronald.araujo&password=123456

The link to original answer: How do I POST urlencoded form data with $http in AngularJS?

like image 145
Huy Hoang Pham Avatar answered Mar 27 '23 23:03

Huy Hoang Pham


You can use $httpParamSerializerJQLike;

.controller(function($http, $httpParamSerializerJQLike) {
  //...

 var serializedUser = $httpParamSerializerJQLike(user);

});

you can see $httpParamSerializerJQLike Documentation here.

like image 26
Mehul Mali Avatar answered Mar 27 '23 21:03

Mehul Mali