如何使用JavaScript安全地编码URL,以便将其放入GET字符串中?
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
我假设您需要在第二行编码myUrl变量?
如何使用JavaScript安全地编码URL,以便将其放入GET字符串中?
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
我假设您需要在第二行编码myUrl变量?
当前回答
为了防止双重编码,最好在编码之前解码URL(例如,如果您处理的是用户输入的URL,可能已经编码)。
假设我们有abc%20xyz 123作为输入(一个空格已编码):
encodeURI("abc%20xyz 123") // Wrong: "abc%2520xyz%20123"
encodeURI(decodeURI("abc%20xyz 123")) // Correct: "abc%20xyz%20123"
其他回答
如前所述,要对URL进行编码,您有两个函数:
encodeURI()
and
encodeURIComponent()
两者都存在的原因是,第一种方法保留了URL,但有可能留下太多未被屏蔽的内容,而第二种方法对所有需要的内容进行编码。
使用第一个,您可以将新转义的URL复制到地址栏中(例如),这样就可以了。然而,未转义的‘&’会干扰字段分隔符,‘=’会干扰域名和值,‘+’看起来像空格。但对于简单的数据,当您希望保留要转义的内容的URL性质时,这是有效的。
第二个是您需要做的一切,以确保字符串中没有任何内容干扰URL。它保留了各种不重要的字符,使URL尽可能保持可读性而不受干扰。以这种方式编码的URL将不再作为URL工作,而不会取消其标题。
因此,如果您可以花点时间,那么在添加名称/值对之前,您总是希望使用encodeURIComponent()对名称和值进行编码,然后再将其添加到查询字符串中。
我很难找到使用encodeURI()的理由——我将把这留给更聪明的人。
您有三个选项:
escape()不会编码:@*/+encodeURI()不会编码:~@#$&*()=:/,;?+'encodeURIComponent()不会编码:~*()'
但在您的情况下,如果要将URL传递到其他页面的GET参数中,则应该使用escape或encodeURIComponent,而不是encodeURI。
有关详细讨论,请参阅堆栈溢出问题最佳实践:转义或encodeURI/encodeURIComponent。
这里是encodeURIComponent()和decodeURIComponent()JavaScript内置函数的现场演示:
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width: 30%;
height: 100px;
}
</style>
<script>
// Encode string to Base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// Decode Base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
坚持使用encodeURIComponent()。函数encodeURI()不需要对URL中具有语义重要性的许多字符进行编码(例如“#”、“?”和“&”)。escape()已被弃用,并且不必对“+”字符进行编码,因为这些字符将在服务器上被解释为已编码的空格(正如其他人在这里指出的,不正确地对非ASCII字符进行URL编码)。
其他地方对encodeURI()和encodeURIComponent()之间的区别有很好的解释。如果您希望对某个内容进行编码,以便它可以安全地作为URI的一个组件(例如作为查询字符串参数)包含,则需要使用encodeURIComponent()。
现代解决方案(2021)
自从编写了其他答案后,就引入了URLSearchParams API。它可以这样使用:
const queryParams = { param1: 'value1', param2: 'value2' }
const queryString = new URLSearchParams(queryParams).toString()
// 'param1=value1¶m2=value2'
它还编码非URL字符。
对于您的具体示例,您可以这样使用:
常量myUrl=“http://example.com/index.html?param=1&anotherParam=2";const myOtherUrl=新URL(“http://example.com/index.html");myOtherUrl.search=新URLSearchParams({url:myUrl});console.log(myOtherUrl.toString());
这个解决方案也在这里和这里提到。