一尘不染

Javascript对象的查询字符串编码

javascript

您是否知道将Javascript对象编码为string可通过GET请求传递的快速简单的方法?

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


阅读 338

收藏
2020-04-25

共1个答案

一尘不染

像这样?

serialize = function(obj) {

  var str = [];

  for (var p in obj)

    if (obj.hasOwnProperty(p)) {

      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));

    }

  return str.join("&");

}



console.log(serialize({

  foo: "hi there",

  bar: "100%"

}));

// foo=hi%20there&bar=100%25

编辑:这也将转换递归对象(使用php“ array”表示法作为查询字符串)

serialize = function(obj, prefix) {

  var str = [],

    p;

  for (p in obj) {

    if (obj.hasOwnProperty(p)) {

      var k = prefix ? prefix + "[" + p + "]" : p,

        v = obj[p];

      str.push((v !== null && typeof v === "object") ?

        serialize(v, k) :

        encodeURIComponent(k) + "=" + encodeURIComponent(v));

    }

  }

  return str.join("&");

}



console.log(serialize({

  foo: "hi there",

  bar: {

    blah: 123,

    quux: [1, 2, 3]

  }

}));

// foo=hi%20there&bar%5Bblah%5D=123&bar%5Bquux%5D%5B0%5D=1&bar%5Bquux%5D%5B1%5D=2&bar%5Bquux%5D%5B2%5D=3
2020-04-25