jQuery.param() takes an array of key-value pairs, and turns it into a string you can use as a query string in HTML requests. For example,
a = {
userid:1,
gender:male
}
would get converted to
userid=1&gender=male
I'm trying to call external APIs on the server side in a Google Apps script, which need long query strings. I would use the jQuery param function, but there seems to be no easy way to use jQuery on the server side in Google.
Could you give me plain javascript code that achieves the same functionality?
The jQuery implementation of it is here, but I don't want to take chances skipping over any crucial details by simply copying it and ripping out the code dealing with 'traditional'.
jQuery param() Method The param() method creates a serialized representation of an array or an object. The serialized values can be used in the URL query string when making an AJAX request.
jQuery works with all modern browsers. There is no such compatibility issue with any browser. No additional plugins are required to run JS.
You can also do that with pure JavaScript, but you have to write more lines of code. Try this:
HTML code for testing:
<p id="test"></p>
JavaScript to be fired onload:
a = {
userid:1,
gender: "male",
}
url = Object.keys(a).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(a[k])
}).join('&')
document.getElementById("test").innerHTML=url
The output is this:
userid=1&gender=male
You can try this on JSFIDDLE.NET, it works, here's the link: http://jsfiddle.net/ert93wbp/
ES6 version that allows to convert nested objects and arrays just use like encodeURI(getUrlString({a: 1, b: [true, 12.3, "string"]}))
.
getUrlString (params, keys = [], isArray = false) {
const p = Object.keys(params).map(key => {
let val = params[key]
if ("[object Object]" === Object.prototype.toString.call(val) || Array.isArray(val)) {
if (Array.isArray(params)) {
keys.push("")
} else {
keys.push(key)
}
return getUrlString(val, keys, Array.isArray(val))
} else {
let tKey = key
if (keys.length > 0) {
const tKeys = isArray ? keys : [...keys, key]
tKey = tKeys.reduce((str, k) => { return "" === str ? k : `${str}[${k}]` }, "")
}
if (isArray) {
return `${ tKey }[]=${ val }`
} else {
return `${ tKey }=${ val }`
}
}
}).join('&')
keys.pop()
return p
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With