问题描述
当编码查询字符串发送到Web服务器 - 什么是JavaScript才能使用的最佳做法:
使用转义:
逃生(%+功放=);
或
使用EN codeURI()/ EN codeURIComponent()
连接codeURI(http://www.google.com?var1=value1&var2=value2);
EN codeURIComponent(VAR1 =值1&放大器; VAR2 =值2);
越狱()
不要使用它,因为它一直以来的ECMAScript V3 pcated德$ P $。
连接codeURI()
当你想要一个工作URL中使用EN codeURI。做这样的判断:
连接codeURI(http://www.google.com/a文件spaces.html)
获得:
http://www.google.com/a%20file%20with%20spaces.html
不要叫EN codeURIComponent,因为它会破坏URL并返回
HTTP%3A%2F%2Fwww.google.com%2FA%20file%20with%20spaces.html
连接codeURIComponent()
当你想连接codeA的URL参数使用EN codeURIComponent。
参数1 = EN codeURIComponent(http://xyz.com/?a=12&b=55)
然后,您可以创建你需要的网址:
URL =http://domain.com/?param1=+参数1 +&放大器;参数2 = 99;
,你会得到这个完整的URL:
<$c$c>http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55¶m2=99$c$c>
需要注意的是EN codeURIComponent没有逃脱字符。一个常见的错误就是用它来创建HTML属性,例如的href ='MyUrl'
,这可能遭受注入漏洞。如果您是从字符串构建HTML,要么使用,而不是为属性的行情,或加入编码额外的一层('可连接codeD为27%)。
有关此类型的编码,您可以检查的详细信息:http://en.wikipedia.org/wiki/Percent-encoding
When encoding a query string to be sent to a web server - what is the best practice to use from javascript:
Use escape:
escape("% +&=");
OR
use encodeURI() / encodeURIComponent()
encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
escape()
Don't use it, as it has been deprecated since ECMAScript v3.
encodeURI()
Use encodeURI when you want a working URL. Make this call:
encodeURI("http://www.google.com/a file with spaces.html")
to get:
http://www.google.com/a%20file%20with%20spaces.html
Don't call encodeURIComponent since it would destroy the URL and return
http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html
encodeURIComponent()
Use encodeURIComponent when you want to encode a URL parameter.
param1 = encodeURIComponent("http://xyz.com/?a=12&b=55")
Then you may create the URL you need:
url = "http://domain.com/?param1=" + param1 + "¶m2=99";
And you will get this complete URL:
http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55¶m2=99
Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create html attributes such as href='MyUrl'
, which could suffer an injection bug. If you are constructing html from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).
For more information on this type of encoding you can check: http://en.wikipedia.org/wiki/Percent-encoding
这篇关于最佳实践:逃生,或EN codeURI / EN codeURIComponent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!