折腾:
【未解决】给绘本查询web版增加点击tag标签搜索
期间,想要对于:
输入一个dict的object,即query string/ query parameter的dict,去实现url参数编码
所以才考虑去:
【未解决】js中获取一个dict对象的key和value
不过突然想要去找找是否有更加高效率的办法
js encode url parameters
可以参考:
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 );
【总结】
目前用:
// 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"