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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:26:58  来源:igfitidea点击:

How serialize objects with angularjs

javascriptjqueryangularjs

提问by Ronald Araújo

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

如何在不使用$.paramjquery 的情况下序列化对象?

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

You can use $httpParamSerializerJQLike;

你可以使用$httpParamSerializerJQLike;

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

 var serializedUser = $httpParamSerializerJQLike(user);

});

you can see $httpParamSerializerJQLikeDocumentation here.

您可以在此处查看$httpParamSerializerJQLike文档。

回答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