问题描述
是否有可能以某种方式将json对象附加到URLSearchParams对象上?
Is it possible to somehow append json objects onto a URLSearchParams object?
所以代替:
urlSearchParams.append('search', 'person');
它是:
urlSearchParams.append({search: "person"});
我的答案由Darshak Gajjar提供答案
可以通过这种方式使用json对象:
Can use json objects via this way:
let test_this = [{"search": "person"}, { search: "another person"}];
var json = JSON.stringify(test_this);
urlSearchParams.append("myobj", json);
return this.http.post(this.post_url, urlSearchParams, options) //options being your own RequestOptions
推荐答案
这样的东西可能有效 urlSearchParams = Object.assign(urlSearchParams,{search:person});
编辑:使用vanilla javascript的替代解决方案。另外,我认为URLSearchParams只是一个普通的js对象,但实际上你必须使用 get
, set
和追加
来访问属性。
Alternate solution using vanilla javascript. Also, I thought URLSearchParams was just a normal js object, but in fact you have to use get
, set
and append
to access properties.
var params = new URLSearchParams("a=apple&b=balloon");
var parametersToAdd = {c: "car", d: "duck"};
for(key in parametersToAdd)
params.append(key, parametersToAdd[key]);
console.log(params.get('c'));
console.log(params.get('d'));
EDIT bis:
.append()
支持重用相同的键/参数名称,而 .set()
会覆盖以前的值。
EDIT bis:.append()
supports to re-use the same key/parameter name, while .set()
would have overwritten a previous value.
这篇关于在URLSearchParams中使用json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!