开发者

What is the recommended way to pass urls as url parameters?

Using &url='+encodeURIComponent(url); to pass a URL from browser to server will encode the url but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the sing开发者_C百科le url parameter.

What is the recommended way to pass urls as url parameters ?


encodeURIComponent() should work. For example,

'&url=' + encodeURIComponent("http://a.com/?q=query&n=10")

produces

"&url=http%3A%2F%2Fa.com%2F%3Fq%3Dquery%26n%3D10"

(which doesn't have any & or ? in the value). When your server gets this url, it should be able to decode that to get the original:

param["url"] = "http://a.com/?q=query&n=10"

I'm not sure what server you're using (e.g. Rails, Django, ...) but that should work "out of the box" on any normal system.


Using '&url='+encodeURIComponent(url); to pass a URL from browser to server will encode the url

Yes, that's what you should be doing. encodeURIComponent is the correct way to encode a text value for putting in part of a query string.

but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the single url parameter.

Then the server is very broken indeed. If that's really what's happening, you need to fix it at the server end.

Code?


I ran into this issue, personally I couldn't use any of the accepted answers, but it can also be done by just encoding the url into Base 64, passing it as a parameter, and then decoding it. With javascript, you can encode a string s to base 64 with btoa(s) and decode with atob(s). Other languages have ways of doing the same thing. Base 64 is just kinda like representing a larger series of characters with 64 character(For ex, all the capital letters, all the lowercase, and a couple symbols). Kinda like how we represent letters in Binary. But it's nice to use, because then we can just pass base64 strings as parameters, and then they won't interfere/get interpreted in a weird fashion, and then we can decode them at the next stage.


Use escape() to url encode it, it will encode the ampersands so that does not happen.


Honestly, go with Google URL Shortener. Then you can just use the URL code in the url query string: http://example.com/url/A7dh3

In your application, take that and prepend the Google URL Shortener domain name, and do the redirect. This adds tracking to the URL through Google Analytics also. Lots of advantages in this approach. Just a short code and added tracking data, too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜