是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?

没有jQuery,没有其他框架-只有纯JavaScript:)


当前回答

好吧,似乎每个人都把他的俏皮话写在这里,所以我的是:

const encoded = Object.entries(obj).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");

其他回答

 let data = {
    id:1,
    name:'Newuser'
    };
const getqueryParam = data => {
  let datasize = Object.keys(data).length;
  let initial = '?';

  Object.keys(data).map(function (key, index) {
    initial = initial.concat(`${key}=${data[key]}`);
    index != datasize - 1 && (initial = initial.concat('&'));
  });
  console.log(initial, 'MyqueryString');
  return initial;
};

console.log(getqueryParam(data))//You can get the query string here

If you have baseUrl means to get full query use 

baseUrl concat (getqueryParam(数据)。

如果您需要发送任意对象,那么GET是一个坏主意,因为有限制的url长度,用户代理和web服务器将接受。我的建议是建立一个名称-值对数组来发送,然后建立一个查询字符串:

function QueryStringBuilder() {
    var nameValues = [];

    this.add = function(name, value) {
        nameValues.push( {name: name, value: value} );
    };

    this.toQueryString = function() {
        var segments = [], nameValue;
        for (var i = 0, len = nameValues.length; i < len; i++) {
            nameValue = nameValues[i];
            segments[i] = encodeURIComponent(nameValue.name) + "=" + encodeURIComponent(nameValue.value);
        }
        return segments.join("&");
    };
}

var qsb = new QueryStringBuilder();
qsb.add("veg", "cabbage");
qsb.add("vegCount", "5");

alert( qsb.toQueryString() );

这里有一个简单的答案,在转换过程中同时处理字符串和数组。

jsonToQueryString: function (data) {
        return Object.keys(data).map((key) => {
            if (Array.isArray(data[key])) {
                return (`${encodeURIComponent(key)}=${data[key].map((item) => encodeURIComponent(item)).join('%2C')}`);
            }
            return(`${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`);
        }).join('&');
    }

const buildSortedQuery = (args) => { 返回种(args) .sort () .map(key => { 返回window.encodeURIComponent(关键) + ' = ' + window.encodeURIComponent (args(例子)); }) . join (' & '); }; console.log (buildSortedQuery ({ Foo:“你好”, 栏:“100%” })); / /酒吧= 100% 25 foo =你好% 20

如果你想将整个对象作为一个参数传递,例如,?filter={param1: "val1", param2: "val2"}:

const serializeObject = (obj) => {
  let objStr = JSON.stringify(obj);

  objStr = objStr.replace(/\{/g, encodeURIComponent("{"));
  objStr = objStr.replace(/}/g, encodeURIComponent("}"));
  objStr = objStr.replace(/:/g, encodeURIComponent(":"));

  return objStr;
};

let res = serializeObject({param1: "val1", param2: "val2"});
console.log("serializeObject:", res); //%7B"param1"%3A"val1","param2"%3A"val2"%7D
console.log("serializeObject-decoded:", decodeURIComponent(res)); //{"param1":"val1","param2":"val2"}