如何使用 JavaScript 在 IE7 中对 location.search 参数进行 urlencode
我注意到 IE7 不会对从 javascript 检索的查询字符串参数进行 url 编码,例如:
var qs = location.search;
在 Firefox 中,对参数进行编码。如何编写 IE 特定的代码,以与 FireFox 相同的方式对参数进行 URL 编码?
例如,在 Firefox 中,此查询字符串:
?val=<script>
//gets rewritten as:
?val=%3Cscript%3E
I have noticed that IE7 does not url-encode querystring parameters retrieved from javascript, e.g:
var qs = location.search;
In Firefox, the parameters are encoded. How can I write IE-specific code to URL-encode the parameters in the same fashion as FireFox?
For example, in Firefox, this querystring:
?val=<script>
//gets rewritten as:
?val=%3Cscript%3E
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,对字符串进行 URL 编码以便在 URL 的一部分中使用的正确函数是
encodeURIComponent
。 不要使用escape
,这是一种过时的、JavaScript独有的非标准自定义编码方案。它看起来像 URL 参数编码,但以不同方式对待加号和所有非 ASCII 字符。将其与标准 URL 解码器放在一起,就会出现错误。但是,如果
或
为您提供了错误字符,则不应通过
location.search
调用encodeURIComponent
。 code> (不应出现在 URL 中,但 IE 允许您输入),因为它会对已经正确编码的字符进行双重编码;例如,地址中的真实%3C
(如果用户遵循正确形式的链接到达您的网站)将被错误转换为%253C
。encodeURI
函数的用途是修复“不安全”的 URL 字符,同时保留已编码的字符;尝试一下(在所有浏览器上,无需嗅探)。它很少使用,但可能是您所需要的。否则,您将看到一个烦人的正则表达式和十六进制编码函数替换。Normally, the correct function to URL-encode a string for use in part of a URL is
encodeURIComponent
. Don't useescape
, which is an obsolescent non-standard custom encoding scheme unique to JavaScript. It looks like URL-parameter-encoding, but treats pluses and all non-ASCII characters differently. Put it together with a standard URL decoder and you get errors.However, you shouldn't call
encodeURIComponent
overlocation.search
if it's giving you bad characters like<
or>
(which shouldn't appear in a URL, but which IE allows you to enter), because it will double-encode characters that are already correctly encoded; for example a real%3C
in the address (from if the user has followed a correctly-formed link to your site) will get mis-converted to%253C
.Fixing up ‘unsafe’ URL characters whilst leaving already-encoded characters alone is what the
encodeURI
function is for; try that (on all browsers, no need for sniffing). It's rarely used, but could be what you need. Otherwise, you're looking at an annoying regexp-and-hex-encoding-function replacement.您可以使用 转义 函数:
You can use the escape function: