Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plain Javascript Equivalent of jQuery.param()

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

like image 355
Neil Avatar asked Aug 10 '14 02:08

Neil


People also ask

What is the use of param () method in jQuery?

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.

Can I use vanilla javascript in jQuery?

jQuery works with all modern browsers. There is no such compatibility issue with any browser. No additional plugins are required to run JS.


2 Answers

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/

like image 58
Amaynut Avatar answered Sep 24 '22 13:09

Amaynut


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
}
like image 32
Boris Barroso Avatar answered Sep 24 '22 13:09

Boris Barroso