user58777
user58777

Reputation:

Support for encoding query string or POST data in YUI?

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.

Upvotes: 0

Views: 3896

Answers (4)

Kevin Hakanson
Kevin Hakanson

Reputation: 42220

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

Upvotes: 0

user58777
user58777

Reputation:

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("&");
    }

Upvotes: 0

foxxtrot
foxxtrot

Reputation: 11412

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.

Upvotes: 0

Christophe Ebl&#233;
Christophe Ebl&#233;

Reputation: 8161

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'});

Upvotes: 2

Related Questions