Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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'.

share|improve this question
up vote 5 down vote accepted

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/

share|improve this answer
1  
Thanks Amynut. That's what I thought it would be, but wanted to make sure I don't miss any subtleties and do it in the most JSic (to Javascript what Pythonic is to Python) way. One subtlety in the jquery implementation is "return s.join("&").replace(r20, "+");". Do you not need actually need that replacement with + signs? MDN suggests that this is relevant when POSTing rather than GETting. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/&h;‌​ellip; – Neil Aug 10 '14 at 15:30
1  
how about nested keys ? you'll need recursion or flatten the object. – alexserver Sep 24 '15 at 0:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.