
如何使用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()不会编码:〜!@#$&amp; </em>()=:/,;?+’<code>< / LI></code> encodeURIComponent()<code>不会编码:</code>〜!*()’<code>但是就你而言,如果你想将一个[ URL](http://en.wikipedia.org/wiki/Uniform_Resource_Locator)传递给</code> GET <code>参数,您应该使用</code>escape <code>或</code> encodeURIComponent <code>,但不要使用</code> encodeURI 。
最佳实践:escape,或encodeURI / encodeURIComponent
请参阅堆栈溢出问题 [最佳做法: / a> 进一步讨论。
未经作者同意,本文严禁转载,违者必究!




近期评论