【问题标题】:Solid javascript encode uri可靠的 javascript 编码 uri
【发布时间】:2016-07-07 08:08:50
【问题描述】:

我已经阅读了这篇文章和更多文章:

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

我仍然没有找到可靠的编码/解码 uri 解决方案。

假设我有这些变量

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=' + 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。

【问题讨论】:

  • 据我所知,encodeURIComponent 用于参数。encodeURI 用于 URL...i.imgur.com/2xKpYd0.png 在您的情况下,# 应使用 encodeURIComponent (%23)当你说它不起作用时,你是什么意思?
  • 您必须更具体地了解“不适用于#”的含义:encodeURIComponent('And "hash,.#$')"And%20%22hash%2C.%23%24"
  • 你试过escape()吗?
  • @Krishnakumar_Muraleedharan 不使用转义,转义和取消转义功能已弃用。 developer.mozilla.org/en/docs/Web/JavaScript/Reference/…

标签: javascript url encode


【解决方案1】:

在编码 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

(来自 w3 school) 这个函数对特殊字符进行编码。在 此外,它还编码以下字符: , / ? : @ & = + $ #

【讨论】:

  • 在每种情况下,每次输入都稳定吗?还是易碎?
  • W3S 的引用很糟糕。 “之外的特殊字符”。什么是“特殊”字符?!更好地引用 MDN:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @Jens 该函数旨在让您可以传输任意值作为 URL 的一部分。所以,是的,它是坚实的。除非你能证明别的......
【解决方案2】:

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

escape('#') 确实产生 %23

【讨论】:

猜你喜欢
  • 2010-11-23
  • 1970-01-01
  • 2011-02-07
  • 2011-02-05
  • 2023-03-07
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多