如何使用 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在第二行对变量进行编码?
查看内置函数encodeURIComponent(str)和encodeURI(str)。
在您的情况下,这应该有效:
var myOtherUrl = 
       "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
您有三个选择:
escape() 不会编码: @*/+
encodeURI() 不会编码: ~!@#$&*()=:/,;?+'
encodeURIComponent() 不会编码: ~!*()'
但是在您的情况下,如果您想将URL传递到GET其他页面的参数中,您应该使用escape或encodeURIComponent,而不是encodeURI。
有关进一步讨论,请参阅堆栈溢出问题最佳实践:转义或 encodeURI / encodeURIComponent。
坚持encodeURIComponent()。该函数encodeURI()不会对 URL 中具有语义重要性的许多字符(例如“#”、“?”和“&”)进行编码。escape()已弃用,并且不会对“+”字符进行编码,这些字符将被解释为服务器上的编码空格(并且,正如其他人所指出的,不能正确地对非 ASCII 字符进行 URL 编码)。
有一个很好的解释encodeURI()和encodeURIComponent()其他地方之间的区别。如果您想对某些内容进行编码,以便可以安全地将其包含为 URI 的组成部分(例如,作为查询字符串参数),您需要使用encodeURIComponent().
最好的答案是使用encodeURIComponent上值的查询字符串(和其他地方)。
但是,我发现许多 API 想要用“+”替换“”,所以我不得不使用以下内容:
const value = encodeURIComponent(value).replace('%20','+');
const url = 'http://example.com?lang=en&key=' + value
escape在不同的浏览器中以不同的方式实现,encodeURI并且不会编码很多字符(例如 # 甚至 /)——它被用于完整的 URI/URL 而不会破坏它——这不是非常有用或安全。
正如@Jochem 在下面指出的那样,您可能希望encodeURIComponent()在(每个)文件夹名称上使用,但无论出于何种原因,这些 API 似乎都不希望+在文件夹名称中使用,因此普通的旧版encodeURIComponent效果很好。
例子:
const escapedValue = encodeURIComponent(value).replace('%20','+');
const escapedFolder = encodeURIComponent('My Folder'); // no replace
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;