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. http://www.google.com, http://www.xyz.com/abc123). The format of the request is as follows:
http://www.mysite.com/[url]
… where [url] is a user provided URL (again, something like http://www.google.com/abc)
I need to URL encode the parameter, as mysite.com/www.google.com is giving me errors.
My problem is, all of the standard javascript encoding functionality does not actually encode the URL.
An example:
<html>
<head>
<script>
document.write("encodeURIComponent = " + encodeURIComponent("www.google.com") + "<br />");
document.write("encodeURI = " + encodeURI("www.google.com") + "<br />");
document.write("escape = " + escape("www.google.com"));
</script>
</head>
<body>
</body>
… has the following output:
encodeURIComponent = www.google.com
encodeURI = www.google.com
escape = www.google.com
What is the proper way to achieve this using JavaScript/jQuery?
I don’t think it’s relevant, but just in case, this is a Rails 3.0.7 app.
EDIT FOR MORE DETAIL
If http://www.google.com is already URL encoded, and periods are fine in my URL (www.mysite.com/www.google.com), why am I getting this error?
From Chrome Dev Tools:
GET http://localhost:3000/s/www.google.com 404 (Not Found)
My jQuery snippet:
$.getJSON("http://localhost:3000/s/" + encodeURI($("#txtURL").val()), function(data) {
alert(data.result.url);
});
This is a perfectly valid URL:
I suspect that you’re just running into the Rails
formatstuff (i.e..htmlat the end of the URL sets the format to HTML,.jsfor JSON, …) so you just need to fix your route to keep the format auto-detection from getting in the way:or
or whatever routing syntax you’re using.
If you don’t tell rails that the
:urlshould 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.