Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function to convert JSON key-value object to query string

I'm working on formatting a URL for the Facebook Feed Dialog. There's so many parameters though. I want to have a function for these dialogs, something like:

function generateDialogUrl(dialog, params) {
  base  = "http://www.facebook.com/dialog/" + dialog + "?";
  tail = [];
  for (var p in params) {
    if (params.hasOwnProperty(p)) {
      tail.push(p + "=" + escape(params[p]));
    }
  }
  return base + tail.join("&")
}

Oh wow... I think I just answered my own question. Is that right? Is escape() the correct function to use?

I'm stuck in the Lovers source code.

UPDATE: Since, we're using jQuery, I rewrote the method using jQuery.each. I also replaced escape() with encodeURIComponent() as suggested by @galambalazs & @T.J. Crowder. Thanks, guys!

var generateDialogUrl = function (dialog, params) {
  base  = "http://www.facebook.com/dialog/" + dialog + "?";
  tail = [];
  $.each(params, function(key, value) {
    tail.push(key + "=" + encodeURIComponent(value));
  })
  return base + tail.join("&");
}

It's working!

like image 583
ma11hew28 Avatar asked Jan 21 '23 12:01

ma11hew28


2 Answers

Better yet, use encodeURIComponent instead. See this article comparing the two:

The escape() method does not encode the + character which is interpreted as a space on the server side as well as generated by forms with spaces in their fields. Due to this shortcoming and the fact that this function fails to handle non-ASCII characters correctly, you should avoid use of escape() whenever possible. The best alternative is usually encodeURIComponent().

escape() will not encode: @*/+

like image 170
25 revs, 4 users 83% Avatar answered Jan 31 '23 06:01

25 revs, 4 users 83%


There is a jQuery method to accomplish this: $.param. It would work like this:

var generateDialogUrl = function (dialog, params) {
  base = 'http://www.facebook.com/dialog/' + dialog + '?';
  return base + $.param(params);
}
like image 24
Irving Avatar answered Jan 31 '23 07:01

Irving