最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】js中如何方便的对于dict的object实现url参数编码

JS crifan 571浏览 0评论
折腾:
【未解决】给绘本查询web版增加点击tag标签搜索
期间,想要对于:
输入一个dict的object,即query string/ query parameter的dict,去实现url参数编码
所以才考虑去:
【未解决】js中获取一个dict对象的key和value
不过突然想要去找找是否有更加高效率的办法
js encode url parameters
javascript – How to encode URL parameters? – Stack Overflow
Query-string encoding of a Javascript Object – Stack Overflow
可以参考:
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
不过也可以直接用:
var params = { width:1680, height:1050 };
var str = jQuery.param( params );
urlencode – JavaScript Array to URLencoded – Stack Overflow
encodeURIComponent() – JavaScript | MDN
encodeURI() – JavaScript | MDN
JavaScript encodeURI() Function
JavaScript encodeURIComponent() Function
【总结】
目前用:
// input:  {q: "", tag: "Shapes and Sizes", difficulty: 2}
// output:  q=&tag=Shapes%20and%20Sizes&difficulty=2
function encodeQueryDict(queryDict){
  console.log("encodeQueryDict: queryDict=%o", queryDict)
  var encodedQueryStr = ""
  if (queryDict){
      var encodedKeyValueStrList = []

      var keyValueList = Object.entries(queryDict)
      console.log("keyValueList=%o", keyValueList)
      for (const [ eachKey, eachValue ] of keyValueList){
          console.log("eachKey=%s, eachValue=%s", eachKey, eachValue)
          var encodedKey = encodeURIComponent(eachKey)
          console.log("encodedKey=%o", encodedKey)
          var encodedValue = encodeURIComponent(eachValue)
          console.log("encodedValue=%o", encodedValue)
          var encodedKeyValueStr = `${encodedKey}=${encodedValue}`
          console.log("encodedKeyValueStr=%o", encodedKeyValueStr)
          encodedKeyValueStrList.push(encodedKeyValueStr)
      }

      console.log("encodedKeyValueStrList=%o", encodedKeyValueStrList)
      if (encodedKeyValueStrList.length > 0){
          encodedQueryStr = encodedKeyValueStrList.join("&")
      }
  }

  console.log("encodedQueryStr=%o", encodedQueryStr)
  return encodedQueryStr
}
实现了:
输入:
encodeQueryDict: queryDict={q: "", tag: "Helping Others", difficulty: 20}
输出:
encodedQueryStr="q=&tag=Helping%20Others&difficulty=20"

转载请注明:在路上 » 【已解决】js中如何方便的对于dict的object实现url参数编码

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
88 queries in 0.109 seconds, using 20.57MB memory