Solid javascript 编码uri

Solid javascript encode uri

我读过这篇文章和更多文章:

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

我仍然没有找到可靠的 encode/decode 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=' + 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 函数的更多信息 here

(citation from w3 school) This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #

您可以尝试使用 escape() 函数。这救了我很多次。

escape('#') 会产生 %23.