2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('querystring-stringify', function(Y) {
11 * Provides Y.QueryString.stringify method for converting objects to Query Strings.
14 * @submodule querystring-stringify
19 var QueryString = Y.namespace("QueryString"),
24 * Provides Y.QueryString.escape method to be able to override default encoding
25 * method. This is important in cases where non-standard delimiters are used, if
26 * the delimiters would not normally be handled properly by the builtin
27 * (en|de)codeURIComponent functions.
28 * Default: encodeURIComponent
30 * @submodule querystring-stringify
34 QueryString.escape = encodeURIComponent;
37 * <p>Converts an arbitrary value to a Query String representation.</p>
39 * <p>Objects with cyclical references will trigger an exception.</p>
43 * @param obj {Variant} any arbitrary value to convert to query string
44 * @param cfg {Object} (optional) Configuration object. The three
45 * supported configurations are:
46 * <ul><li>sep: When defined, the value will be used as the key-value
47 * separator. The default value is "&".</li>
48 * <li>eq: When defined, the value will be used to join the key to
49 * the value. The default value is "=".</li>
50 * <li>arrayKey: When set to true, the key of an array will have the
51 * '[]' notation appended to the key. The default value is false.
53 * @param name {String} (optional) Name of the current key, for handling children recursively.
56 QueryString.stringify = function (obj, c, name) {
57 var begin, end, i, l, n, s,
58 sep = c && c.sep ? c.sep : "&",
59 eq = c && c.eq ? c.eq : "=",
60 aK = c && c.arrayKey ? c.arrayKey : false;
62 if (L.isNull(obj) || L.isUndefined(obj) || L.isFunction(obj)) {
63 return name ? QueryString.escape(name) + eq : '';
66 if (L.isBoolean(obj) || Object.prototype.toString.call(obj) === '[object Boolean]') {
70 if (L.isNumber(obj) || L.isString(obj)) {
71 return QueryString.escape(name) + eq + QueryString.escape(obj);
76 name = aK ? name + '[]' : name;
78 for (i = 0; i < l; i++) {
79 s.push( QueryString.stringify(obj[i], c, name) );
84 // now we know it's an object.
86 // Check for cyclical references in nested objects
87 for (i = stack.length - 1; i >= 0; --i) {
88 if (stack[i] === obj) {
89 throw new Error("QueryString.stringify. Cyclical reference");
95 begin = name ? name + '[' : '';
96 end = name ? ']' : '';
98 if (obj.hasOwnProperty(i)) {
100 s.push(QueryString.stringify(obj[i], c, n));