How to encode a URL for passing it as a GET parameter

你。 提交于 2020-01-17 03:35:06

问题


I load a JavaScript file which takes current page's URL as a parameter. Here is the code I use:

document.write(unescape('%3Cscript src=\"' + _vis_opt_protocol + 'domain.com/js.php&a='+account_id+'&url='+encodeURIComponent(document.URL)+'&random='+Math.random()+'\" type=\"text/javascript\"%3E%3C/script%3E'));

I thought encodeURIComponent will do the job of properly encoding the URL. However, while loading JS file, browsers interpret the encoded URL too. For example if the document.URL is http://example.com/?test=1#nono then the browser interprets test as another parameter to JS and doesn't send anything after (and including) #nono because it thinks it is an anchor.

What is the best way to encode the URL so that it is passed as it is to the server? I was also toying with base64 or some other form of encoding.


回答1:


The problem is that the unescape function you are calling undoes do job of encodeURIComponent. You may try this:

document.write('<script type="text/javascript" src="' + _vis_opt_protocol + 'domain.com/js.php&a=' + account_id + '&url=' + encodeURIComponent(document.URL) + '&random=' + Math.random() + '"><\/sc' + 'ript>');


来源:https://stackoverflow.com/questions/2672747/how-to-encode-a-url-for-passing-it-as-a-get-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!