你如何使用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
。
参见Stack Overflow问题最佳实践:escape,或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='
+值
escape
在不同的浏览器中的实现方式不同,而encodeURI
并没有对很多字符进行编码(比如#甚至是/)--它是为了在不破坏完整的URI/URL的情况下使用--这并不是超级有用或安全的。
正如 @Jochem 在下面指出的,你可能想在一个(每个)文件夹名上使用 encodeURIComponent()
,但不管什么原因,这些 API 似乎不希望在文件夹名中出现 +
,所以普通的老式 encodeURIComponent
效果很好。
例子:```javascript
const escapedValue = encodeURIComponent(value).replace('%20','+')。
const escapedFolder = encodeURIComponent('My Folder');
//没有替换
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`。
要对一个URL进行编码,就像之前说过的,你有两个函数。
encodeURI()
和
encodeURIComponent()
两种方式存在的原因是,第一种方式保留了URL,但有可能会留下太多未被转义的内容,而第二种方式则对所有需要的内容进行编码。
使用第一种方法,你可以将新转义的URL复制到地址栏中(例如),这样就可以了。 然而你的未转义的'&'s会干扰字段定界符,'='s会干扰字段名和值,而'+'s会看起来像空格。 但是对于简单的数据来说,当你想保留你要转义的东西的URL性质时,这就可以了。
第二个是你需要做的一切,以确保你的字符串中没有任何东西会干扰URL。 它将各种不重要的字符未被逃逸,这样URL就会尽可能的保持可读性,不受干扰。 以这种方式编码的URL,如果不解压缩,将无法再作为URL使用。
所以,如果你能花时间,你总是想使用 encodeURIComponent() -- 在添加名称/值对之前,使用这个函数对名称和值进行编码,然后再将其添加到查询字符串中。
我很难想出使用 encodeURI()的理由--我会把这个问题留给更聪明的人。
encodeURIComponent()就是这样的。
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
但是你应该记住,这和php版本的urlencode()
有细微的差别,而且正如@CMS所提到的,它不会对每个字符进行编码。
http://phpjs.org/functions/urlencode/ 的人做了相当于phpencode()
的js。
function urlencode(str) {
str = (str + '').toString();
// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
// PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
return encodeURIComponent(str)
.replace('!', '%21')
.replace('\'', '%27')
.replace('(', '%28')
.replace(')', '%29')
.replace('*', '%2A')
.replace('%20', '+');
}
对我来说没有任何工作。 我看到的只是登录页面的HTML,回到客户端的代码是200。 一开始是302,但同样的Ajax请求在另一个Ajax请求里面加载登录页面,这应该是一个重定向而不是加载登录页面的纯文本)。
在登录控制器中,我添加了这一行。
Response.Headers["land"] = "login";
而在全局Ajax处理程序中,我这样做了。
$(function () {
var $document = $(document);
$document.ajaxSuccess(function (e, response, request) {
var land = response.getResponseHeader('land');
var redrUrl = '/login?ReturnUrl=' + encodeURIComponent(window.location);
if(land) {
if (land.toString() === 'login') {
window.location = redrUrl;
}
}
});
});
现在,我没有任何问题,它像一个魅力。
当URL内有特殊字符时,应该对其进行编码。 例如
<!--开始片段。 js hide: false console: true babel.false --> -- begin snippet: js hide: false console: true false -->
console.log(encodeURIComponent('?notEncoded=&+'));
<!--结束片段-->
在这个例子中,我们可以观察到,除了字符串notEncoded
之外,所有的字符都用%符号编码。
URL编码也被称为百分比编码,因为它将所有的特殊字符都用%符号转义。
那么在这个%号之后,每个特殊字符都有一个唯一的编码。
某些字符在URL字符串中具有特殊的值。 例如,? 字符表示查询字符串的开始。 为了在网络上成功定位一个资源,需要区分一个字符是字符串的一部分还是url结构的一部分。
JS提供了一堆内置的实用函数,我们可以用它来轻松地对URL进行编码's。 这是两个方便的选项。
encodeURIComponent()
。
将URI的一个组件作为参数,并返回编码后的URI字符串。encodeURI()
:取一个URI的组件作为参数,并返回编码后的URI字符串。
取一个URI作为参数,并返回编码后的URI字符串。
注意不要将整个URL(包括方案,如https://)传入encodeURIComponent()
。
这实际上可能会将其转化为一个无法使用的URL。
例如:<!-- begin snipp()。
false -->
// for a whole URI don't use encodeURIComponent it will transform
// the / characters and the URL won't fucntion properly
console.log(encodeURIComponent("http://www.random.com/specials&char.html"));
// instead use encodeURI for whole URL's
console.log(encodeURI("http://www.random.com/specials&char.html"));
<!--结束片段-->
我们可以观察到,如果我们把整个URL放在encodeURIComponent
中,那么前进的斜线(/)也被转换为特殊字符。
这将导致URL无法正常运行了。
因此(顾名思义)使用。
encodeURIComponent
在您要编码的URL的某一部分上使用。encodeURI
在您要编码的整个URL上。
Encode URL String
var url = $(location).attr('href'); //获取当前url //OR var url = '文件夹/index.html?param=#23dd&noob=yes'。 //或指定一个var encodedUrl = encodeURIComponent(url); console.log(encodedUrl); //outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes for more info go http://www.sitepoint.com/jquery-decode-url-string
你可以使用esapi库并使用下面的函数对你的url进行编码。 该函数确保'/' 不丢失,而其余的文本内容则被编码。
function encodeUrl(url)
{
String arr[] = url.split("/");
String encodedUrl = "";
for(int i = 0; i<arr.length; i++)
{
encodedUrl = encodedUrl + ESAPI.encoder().encodeForHTML(ESAPI.encoder().encodeForURL(arr[i]));
if(i<arr.length-1) encodedUrl = encodedUrl + "/";
}
return url;
}
[https://www.owasp.org/index.php/ESAPI_JavaScript_Readme][1]
[1]: https://www.owasp.org/index.php/ESAPI_JavaScript_Readme
这里是 "encodeURIComponent() "和 "decodeURIComponent() "JS内置函数的[LIVE DEMO][1]。
<!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>
[1]: https://codverter.com/src/webeditor?query=64199300-c557-4048-b924-c2561dcfbf17