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'.
This was a bit frustrating. None of the solutions here seemed to actually work to produce actual "x-www-form-urlencoded" data for any JSON object, the equivalent of JQuery. Some came close but failed on child items. I pieced code from a few of the solutions to get this, working version for any JSON object:
FYI I had to use this for FastSpring's API, because for some freaky reason they only accept x-www-form-urlencoded data in 2020. Spent all day on this because this is the first time in almost a decade an API didn't just accept JSON :(
@Amaynut's answer is awesome. But I do some simplify:
or maybe modulize it using es6 module:
util.js
and use like this:
See it in action here: https://www.webpackbin.com/bins/-KnpOI6hb1AzTDpN3wS7
You can also do that with pure JavaScript, but you have to write more lines of code. Try this:
HTML code for testing:
JavaScript to be fired onload:
The output is this:
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"]}))
.