javascript 如何使用 angularjs 序列化对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29382004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How serialize objects with angularjs
提问by Ronald Araújo
How can I serialize an object without using the $.param
jquery?
如何在不使用$.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.
有什么建议?记住我会使用 Angularjs 或纯 Javascript 来做到这一点。
EDIT:
编辑:
I am using the verb "save" ($resource) the angularjs. How could I set the header "application / x-www-form-urlencoded" and serialize?
我在 angularjs 中使用动词“保存”($resource)。如何设置标题“application / x-www-form-urlencoded”并序列化?
回答by Huy Hoang Pham
Pure javascript can do it just fine:
纯 javascript 可以做到:
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?
原始答案的链接:How do I POST urlencoded form data with $http in AngularJS?
回答by Mehul Mali
回答by 0x1ad2
For angular 2 I think you can best use the following decorator https://github.com/pleerock/class-transformerto transform, serialize and deserialize objects.
对于 angular 2,我认为您最好使用以下装饰器https://github.com/pleerock/class-transformer来转换、序列化和反序列化对象。
To learn more about decorators see https://angular.io/docs/ts/latest/cookbook/ts-to-js.html
要了解有关装饰器的更多信息,请参阅https://angular.io/docs/ts/latest/cookbook/ts-to-js.html