export class Compentency {
competencies : number[];
}
postData() {
let array = [1, 2, 3];
this.comp.competencies = array;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers, method: 'post' });
return this.http.post(this.postUrl, JSON.stringify(this.comp), options)
.map(res => res.json().data.competencies)
.catch(this.handleError);
}
答案 0 :(得分:5)
application / x-www-form-urlencoded
转义控件名称和值。空格字符由+', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by
%HH'替换,百分号和两个十六进制数字表示字符的ASCII代码。换行符表示为" CR LF"对(即%0D%0A').
The control names/values are listed in the order they appear in the document. The name is separated from the value by
='和名称/值对通过`&'彼此分开。
因此,您需要转换JSON对象。 我只是迭代JSON并输出: encodeURIComponent(propertyKey)+" =" + encodeURIComponent(propertyValue)并将使用&组合它们。标志。 e.g。
var str = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]))
console.log(key + " -> " + obj[key]);
}
}
return str.join("&");
答案 1 :(得分:2)
使用querystring,
npm install querystring
var querystring = require('querystring')
var inputJson = {
name: "Asdf",
age: 23
}
console.log(querystring.stringify(inputJson))
这会将您的json转换为application / x-www-form-urlencoded
答案 2 :(得分:2)
let o = { a:1, b:'2', c:true };
let s = new URLSearchParams(Object.entries(o)).toString();
console.log(s);
答案 3 :(得分:1)
假设有一个名为postdata的对象,如下所示:
const postdata = {
'a':1,
'b':2,
'c':3
};
,并且您希望将其转换为x-www-form-urlencoded格式,例如:a=1&b=2&c=3
使用URLSearchParams十分容易。
const rawData = new URLSearchParams(Object.keys(postdata).map(key=>[key,postdata[key]]));
console.log(rawData.toString());//a=1&b=2&c=3
答案 4 :(得分:1)
我在问题 fetch polyfill repo 中找到了最简单的解决方案。
// params -> the JSON object to convert
const searchParams = Object.keys(params).map((key) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
它对我有用,我也希望对你有用。
答案 5 :(得分:0)
非递归变体可以使用ES6 / TypeScript表示为单行:
const formEncodedBody = Object.keys(obj).filter(k => obj.hasOwnProperty(k)).map(
k => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k])).join('&');
请注意,此算法(以及其他解决方案)也有一些假设:
答案 6 :(得分:-1)
<ul id="iconType">
<li><a href="javascript:;" id="circleIcons">Circle icons</a></li>
<li><a href="javascript:;" id="squareIcons">Square icons</a></li>
<li><a href="javascript:;" id="grayIcons">Gray icons</a></li>
<li><a href="javascript:;" id="sketchIcons">Sketch icons</a></li>
</ul>
<div id="selectedIcons">
<img src="/Images/facebook-circle-icon.png" />
<img src="/Images/twitter-circle-icon.png" />
<img src="/Images/linkedin-circle-icon.png" />
<img src="/Images/youtube-circle-icon.png" />
</div>