Skip to content Skip to sidebar Skip to footer

How Do I Url Encode A Url Parameter That Is Itself A Url?

Quick background - I am making a jQuery ajax call to a service I wrote that returns a JSON response. The service accepts a web site URL (i.e. www.google.com, www.xyz.com/abc123). T

Solution 1:

This is a perfectly valid URL:

http://mysite.com/s/www.google.com

I suspect that you're just running into the Rails format stuff (i.e. .html at the end of the URL sets the format to HTML, .js for JSON, ...) so you just need to fix your route to keep the format auto-detection from getting in the way:

map.connect'/s/:url', :requirements => { :url =>/.*/ }, ...

or

match '/s/:url' => 'pancakes#house', :constraints => { :url =>/.*/ }, ...

or whatever routing syntax you're using.

If you don't tell rails that the :url should match /.*/ (i.e. anything at all), it will try to interpret the periods in the route as format specifiers, that will fail and Rails will 404 because it can't figure out how to route the URL.

Solution 2:

URL encoding escapes characters that have a special meaning in the URL (like / and ?) and/or aren't ASCII characters. http://mysite.com/www.google.com is a perfectly valid URL, there's nothing to escape. If you'd include the protocol as well, you'd get some escape-worthy characters:

encodeURIComponent('http://www.google.com')
"http%3A%2F%2Fwww.google.com"

If your server 404s on a request to http://localhost:3000/s/www.google.com, that means the URL isn't handled by the server. It doesn't mean that the URL is invalid.

Solution 3:

As mu said dots don't need to be encoded. The jQuery-way for building a proper QUERY_STRING would be the use of $.param()

$.param({encodeURIComponent:'http://www.google.de'})

Post a Comment for "How Do I Url Encode A Url Parameter That Is Itself A Url?"