问题
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