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). The format of the request is as follows:
http://www.mysite.com/[url]
... where [url] is a user provided URL (again, something like 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 开发者_Go百科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 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:
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.
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.
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'})
精彩评论