io-query.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. define(["./_base/lang"], function(lang){
  2. // module:
  3. // dojo/io-query
  4. var backstop = {};
  5. return {
  6. // summary:
  7. // This module defines query string processing functions.
  8. objectToQuery: function objectToQuery(/*Object*/ map){
  9. // summary:
  10. // takes a name/value mapping object and returns a string representing
  11. // a URL-encoded version of that object.
  12. // example:
  13. // this object:
  14. //
  15. // | {
  16. // | blah: "blah",
  17. // | multi: [
  18. // | "thud",
  19. // | "thonk"
  20. // | ]
  21. // | };
  22. //
  23. // yields the following query string:
  24. //
  25. // | "blah=blah&multi=thud&multi=thonk"
  26. // FIXME: need to implement encodeAscii!!
  27. var enc = encodeURIComponent, pairs = [];
  28. for(var name in map){
  29. var value = map[name];
  30. if(value != backstop[name]){
  31. var assign = enc(name) + "=";
  32. if(lang.isArray(value)){
  33. for(var i = 0, l = value.length; i < l; ++i){
  34. pairs.push(assign + enc(value[i]));
  35. }
  36. }else{
  37. pairs.push(assign + enc(value));
  38. }
  39. }
  40. }
  41. return pairs.join("&"); // String
  42. },
  43. queryToObject: function queryToObject(/*String*/ str){
  44. // summary:
  45. // Create an object representing a de-serialized query section of a
  46. // URL. Query keys with multiple values are returned in an array.
  47. //
  48. // example:
  49. // This string:
  50. //
  51. // | "foo=bar&foo=baz&thinger=%20spaces%20=blah&zonk=blarg&"
  52. //
  53. // results in this object structure:
  54. //
  55. // | {
  56. // | foo: [ "bar", "baz" ],
  57. // | thinger: " spaces =blah",
  58. // | zonk: "blarg"
  59. // | }
  60. //
  61. // Note that spaces and other urlencoded entities are correctly
  62. // handled.
  63. // FIXME: should we grab the URL string if we're not passed one?
  64. var dec = decodeURIComponent, qp = str.split("&"), ret = {}, name, val;
  65. for(var i = 0, l = qp.length, item; i < l; ++i){
  66. item = qp[i];
  67. if(item.length){
  68. var s = item.indexOf("=");
  69. if(s < 0){
  70. name = dec(item);
  71. val = "";
  72. }else{
  73. name = dec(item.slice(0, s));
  74. val = dec(item.slice(s + 1));
  75. }
  76. if(typeof ret[name] == "string"){ // inline'd type check
  77. ret[name] = [ret[name]];
  78. }
  79. if(lang.isArray(ret[name])){
  80. ret[name].push(val);
  81. }else{
  82. ret[name] = val;
  83. }
  84. }
  85. }
  86. return ret; // Object
  87. }
  88. };
  89. });