如何将JS对象数据转换为x-www-form-urlencoded [英] How to convert JS object data to x-www-form-urlencoded

查看:639
本文介绍了如何将JS对象数据转换为x-www-form-urlencoded的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将JS对象转换为x-www-form-urlencoded.如何在角度2中做到这一点?

I wish to convert a JS object into x-www-form-urlencoded. How can I achieve this in angular 2?

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);
    }

推荐答案

application/x-www-form-urlencoded

转义控件名称和值.空格字符用 +'替换,然后按[RFC1738]第2.2节中的描述转义保留的字符:非字母数字字符替换为%HH',一个百分号和两个十六进制数字,分别表示字符的ASCII码.换行符表示为"CR LF"对(即%0D%0A').控件名称/值以它们在文档中出现的顺序列出.名称与值之间用 ='分隔,名称/值对之间由'&'分隔.

Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by=' and name/value pairs are separated from each other by `&'.

因此,您将需要转换JSON对象.我只是简单地遍历JSON和输出:encodeURIComponent(propertyKey)+"=" + encodeURIComponent(propertyValue)并将使用&标志.例如

Therefore you will need to transform your JSON object. I would simply iterate over the JSON and output: encodeURIComponent(propertyKey) + "=" + encodeURIComponent(propertyValue) and will combine them using the & sign. 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("&");

这篇关于如何将JS对象数据转换为x-www-form-urlencoded的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆