3 Copyright 2012 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
7 YUI.add('querystring-stringify', function(Y) {
10 * Provides Y.QueryString.stringify method for converting objects to Query Strings.
13 * @submodule querystring-stringify
18 var QueryString = Y.namespace("QueryString"),
23 * Provides Y.QueryString.escape method to be able to override default encoding
24 * method. This is important in cases where non-standard delimiters are used, if
25 * the delimiters would not normally be handled properly by the builtin
26 * (en|de)codeURIComponent functions.
27 * Default: encodeURIComponent
29 * @submodule querystring-stringify
33 QueryString.escape = encodeURIComponent;
36 * <p>Converts an arbitrary value to a Query String representation.</p>
38 * <p>Objects with cyclical references will trigger an exception.</p>
42 * @param obj {Variant} any arbitrary value to convert to query string
43 * @param cfg {Object} (optional) Configuration object. The three
44 * supported configurations are:
45 * <ul><li>sep: When defined, the value will be used as the key-value
46 * separator. The default value is "&".</li>
47 * <li>eq: When defined, the value will be used to join the key to
48 * the value. The default value is "=".</li>
49 * <li>arrayKey: When set to true, the key of an array will have the
50 * '[]' notation appended to the key. The default value is false.
52 * @param name {String} (optional) Name of the current key, for handling children recursively.
55 QueryString.stringify = function (obj, c, name) {
56 var begin, end, i, l, n, s,
57 sep = c && c.sep ? c.sep : "&",
58 eq = c && c.eq ? c.eq : "=",
59 aK = c && c.arrayKey ? c.arrayKey : false;
61 if (L.isNull(obj) || L.isUndefined(obj) || L.isFunction(obj)) {
62 return name ? QueryString.escape(name) + eq : '';
65 if (L.isBoolean(obj) || Object.prototype.toString.call(obj) === '[object Boolean]') {
69 if (L.isNumber(obj) || L.isString(obj)) {
70 return QueryString.escape(name) + eq + QueryString.escape(obj);
75 name = aK ? name + '[]' : name;
77 for (i = 0; i < l; i++) {
78 s.push( QueryString.stringify(obj[i], c, name) );
83 // now we know it's an object.
85 // Check for cyclical references in nested objects
86 for (i = stack.length - 1; i >= 0; --i) {
87 if (stack[i] === obj) {
88 throw new Error("QueryString.stringify. Cyclical reference");
94 begin = name ? name + '[' : '';
95 end = name ? ']' : '';
97 if (obj.hasOwnProperty(i)) {
99 s.push(QueryString.stringify(obj[i], c, n));
113 }, '3.5.1' ,{requires:['yui-base'], supersedes:['querystring-stringify-simple']});