views:

984

answers:

4

How do you encode a javascript object/hash (pairs of properties and values) into a URL-encoded query string with YUI (2.7.0 or 3.0.0 Beta) ?

I want to do the equivalent of Object.toQueryString() from Prototype:

I need this to encode parameters for GET and POST requests with YAHOO.util.Connect.

It turns out YAHOO.util.Connect has a setForm() method to serialize a form but that still leaves me out cold to encode parameters for GET requests, or the 4th parameter of YAHOO.util.Connect.asyncRequest() to pass post data.

+1  A: 

I've made this little helper for my own project.

var toQueryString = function(o) {
    if(typeof o !== 'object') {
        return false;
    }
    var _p, _qs = [];
    for(_p in o) {
        _qs.push(encodeURIComponent(_p) + '=' + encodeURIComponent(o[_p]));
    }
    return _qs.join('&');
};

// And to use it
var qs = toQueryString({'foo' : 'bar'});
SleepyCod
A: 

YUI3 has the io-form module, which you can instantiate in your call the use. It allows you to write code like this:

YUI().use('node', 'io-form', function(Y) {
 Y.get('#formId').on('sumbit', function(e) {
     e.preventDefault();
     Y.io(postURL,
     {
         method: "POST",
         on: {
             complete: on_complete_handler
         },
         form: {
             id: "formId"
         }
     });
    }
});

This code will make a POST request to postURL, with all the input values from the form with id "formId" is submitted. This module also works for GET requests.

foxxtrot
My question is about encoding a javascript hash/Object. Regarding form, YUI 2.7.0 Connection Manager provides a setForm() method.
faB
A: 

I ended up using something like this based on some code found on github. The function must handle posting arrays..

"Y" is a reference to "YAHOO"

    /**
     * Turns an object into its URL-encoded query string representation.
     *
     * @param {Object} obj   Parameters as properties and values 
     */
    toQueryString: function(obj, name) {

        var i, l, s = [];

        if (Y.lang.isNull(obj) || Y.lang.isUndefined(obj)) {
        return name ? encodeURIComponent(name) + '=' : '';
      }

        if (Y.lang.isBoolean(obj)) {
        obj = obj ? 1 : 0;
      }

      if (Y.lang.isNumber(obj) || Y.lang.isString(obj)) {
        return encodeURIComponent(name) + '=' + encodeURIComponent(obj);
      }

      if (Y.lang.isArray(obj)) {
        name = name; // + '[]'; don't do this for Java (php thing)
        for (i = 0, l = obj.length; i < l; i ++) {
          s.push(arguments.callee(obj[i], name));
        }
        return s.join('&');
      }

      // now we know it's an object.
      var begin = name ? name + '[' : '',
          end = name ? ']' : '';
      for (i in obj) {
        if (obj.hasOwnProperty(i)) {
         s.push(arguments.callee(obj[i], begin + i + end));
        }
      }

      return s.join("&");
    }
faB
A: 

I see YUILibrary Ticket 2528174 refers to an accepted contribution on for this.

The Querystring Utility
    Provides static methods to serialize objects to querystrings and deserialize objects from querystrings.

    Three modules are available:
        querystring           - Both parse and stringify functionality
        querystring-parse     - Parse valid querystring into JavaScript objects
        querystring-stringify - Serialize JavaScript objects into valid query strings
Kevin Hakanson