如何编码URL作为GET参数传递 [英] How to encode a URL for passing it as a GET parameter

查看:140
本文介绍了如何编码URL作为GET参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我加载一个将当前页面的URL作为参数的JavaScript文件。这是我使用的代码:

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'));

我认为encodeURIComponent会做正确编码URL的工作。但是,当加载JS文件时,浏览器也会解码编码的URL。例如,如果document.URL是 http://example.com/?test=1#nono 然后浏览器将测试解释为JS的另一个参数,并且不会在(和包括)#nono之后发送任何内容,因为它认为它是一个锚点。

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.

对URL进行编码的最佳方式是什么,以便将其传递到服务器?我也是用base64或其他一些形式的编码。

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.

推荐答案

问题是 unescape 函数你正在调用undoes做工作的 encodeURIComponent 。您可以尝试以下方式:

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>');

这篇关于如何编码URL作为GET参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆