在JavaScript中编码URL?
你如何安全地使用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 。
请参阅堆栈溢出问题最佳实践:使用escape或encodeURI / encodeURIComponent进行进一步讨论。
坚持encodeURIComponent() 。 encodeURI()函数不会编码许多在URL中具有语义重要性的字符(例如“#”,“?”和“&”)。 不推荐使用escape() ,并且不打算编码“+”字符,这将被解释为服务器上的编码空间(并且正如此处其他人所指出的,未正确地对非ASCII字符进行URL编码)。
有关encodeURI()和encodeURIComponent()在其他地方的区别的一个很好的解释。 如果你想编码一些东西,以便它可以安全地作为一个URI的一部分被包含(例如作为一个查询字符串参数),你想使用encodeURIComponent() 。
上一篇: Encode URL in JavaScript?
下一篇: How do you disable browser Autocomplete on web form field / input tag?
