Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery param alternative for javascript

I need to convert following type dictionary:

{'key1': ['value1'], 'key2': ['value1', 'value2']}

to key1=value1&key2=....

i.e. post data form. I am doing this inside chrome extention, the above dictionary of formdata is returned by:

chrome.webRequest.onBeforeRequest.addListener(function(details) {
      if(details.method=="POST")         // ajax call
      {
        message.postdata = details.requestBody.formData;
      }
      return {requestHeaders: details.requestHeaders};
 }, {urls: ["<all_urls>"],types: ["main_frame", "sub_frame"]}, ["blocking", "requestBody"]);

I remeber achieving the same using JQuery $.params() function. How can the same be done in javascript.

like image 900
adnan kamili Avatar asked Mar 22 '14 19:03

adnan kamili


2 Answers

function queryParams(source) {
  var array = [];

  for(var key in source) {
     array.push(encodeURIComponent(key) + "=" + encodeURIComponent(source[key]));
  }

  return array.join("&");
}
like image 52
Joey Avatar answered Oct 06 '22 06:10

Joey


This is a mini jquery param API [fiddle].

You can use it through jqMini.param(obj);

as shown in the fiddle above, it provides the same output with jquery's original $.param function.

Note: jqMini.param does not handle the traditional jquery objects as parameters.

(function(w) {
    var app = {},
        class2type = {},
        toString = class2type.toString,
        r20 = /%20/g,
        rbracket = /\[\]$/;
    
    w.jqMini = app;
    
    app.type = function(obj) {
        if ( obj == null ) {
            return obj + "";
        }
        // Support: Android < 4.0, iOS < 6 (functionish RegExp)
        return typeof obj === "object" || typeof obj === "function" ?
            class2type[ toString.call(obj) ] || "object" :
        typeof obj;
    };
    
    app.isFunction = function(obj) {
        return app.type(obj) === "function";
    };
    
    app.buildParams = function(prefix, obj, add) {
        var name, key, value;
        
        if(Array.isArray(obj)) {
            for(var key in obj) {
                value = obj[key]
                if(rbracket.test(prefix))
                    add(prefix, value);
                else
                    app.buildParams(prefix + "[" + (typeof value === "object"? key: "") + "]", value, add );
            }
        } else if(app.type(obj) === 'object') {
            for(name in obj)
                app.buildParams(prefix + "[" + name + "]", obj[name], add);
        } else
            add(prefix, obj);
    };
    
    app.param = function(obj) {
        var prefix, key, value
        serialized = [],
            add = function(key, value) {
                value = app.isFunction(value)? value() : (value == null ? "" : value );
                serialized[serialized.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
            };
        
        if(Array.isArray(obj)) {
            for(key in obj) {
                value = obj[key];
                add(key, value);
            }
        } else {
            for(prefix in obj)
                app.buildParams(prefix, obj[prefix], add);
        }
        
        return serialized.join('&').replace(r20, '+');
    };
    
})(window);

var obj = {'key1': ['value1'], 'key2': ['value1', 'value2']};
console.log(jqMini.param(obj));
like image 35
ryeballar Avatar answered Oct 06 '22 07:10

ryeballar