io-query.js 2.9 KB

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