实心javascript编码uri
我读过这篇和更多的文章: 我仍然没有找到一个可靠的编码/解码uri解决方案 假设我有这些变量实心javascript编码uri,javascript,url,encode,Javascript,Url,Encode,我读过这篇和更多的文章: 我仍然没有找到一个可靠的编码/解码uri解决方案 假设我有这些变量 var first = 'Hello&and'; var second = "Let's have cite"; var third = 'And "hash,.#$'; var fourth = 'åäö other strange chars'; 未编码的url应为: var url 'http://example.com/?first=' + first + '&second=
var first = 'Hello&and';
var second = "Let's have cite";
var third = 'And "hash,.#$';
var fourth = 'åäö other strange chars';
未编码的url应为:
var url 'http://example.com/?first=' + first + '&second=' + second + '&third=' + third + '&fourth=' + fourth;
稍后,它将出现在ajax请求中,如:
xhr = new XMLHttpRequest();
xhr.open('POST', url );
我试过这个:
var url 'http://example.com/?first=' + encodeURIComponent(first);
但它不适用于#
。那么,对于所有字符,什么是可靠的编码解决方案呢
我不使用jQuery,只使用javascript。在编码uri参数时使用
encodeURIComponent
。使用该函数对哈希标记进行编码时,将生成字符串“%23”
在你的例子中:
var first = 'Hello&and';
var second = "Let's have cite";
var third = 'And "hash,.#$';
var fourth = 'åäö other strange chars';
var url = 'http://example.com/?first=' + encodeURIComponent(first) + '&second=' + encodeURIComponent(second) + '&third=' + encodeURIComponent(third) + '&fourth=' + encodeURIComponent(fourth);
将导致url变量包含以下字符串:
http://example.com/?first=Hello%26and&second=Let's%20have%20cite&third=And%20%22hash%2C.%23%24&fourth=%C3%A5%C3%A4%C3%B6%20other%20strange%20chars
可以找到encodeURIComponent
功能的更多信息
(引用自w3学校)此函数对特殊字符进行编码。在里面
此外,它对以下字符进行编码:,/?:@&=+$#
您可以尝试使用
escape()
函数。这救了我很多次
escape(“#”)
确实会产生%23
,据我所知encodeURIComponent
用于参数。。而encodeURI
用于URL。。。在你的例子中,#
应该使用encodeURIComponent
(%23)当你说它不工作时,你是什么意思?你必须更具体地说明什么“不工作于#
”意味着:encodeURIComponent('And“hash,.#$”)
→ “和%20%22hash%2C.%23%24”
。您是否尝试过使用escape()
?@Krishnakumar_Muraleedharan不使用escape,escape和unescape函数已被弃用。它是否在每种情况下都是可靠的?或者是可破坏的?W3S引用非常糟糕。”除了@Jens之外,该函数还包含特殊字符,因此您可以将任意值作为URL的一部分进行传输。所以,是的,它是实心的。除非你能证明不是这样,否则escape和unescape函数是不推荐使用的。