简体   繁体   English

为什么字符编码对URL很重要?

[英]Why is character encoding important for URLs?

I'm currently learning JavaScript, and I don't understand why it is important to encode URLs. 我目前正在学习JavaScript,但我不明白为什么对URL进行编码很重要。

>>> var url = 'http://www.packtpub.com/scr ipt.php?q=this and that';
>>> encodeURI(url);

"http://www.packtpub.com/scr%20ipt.php?q=this%20and%20that" “ http://www.packtpub.com/scr%20ipt.php?q=this%20and%20that”

For instance, in this example what purpose would it serve to change the first URL to the latter one. 例如,在此示例中,将第一个URL更改为后一个URL的目的是什么。

It depends on what you're going to be doing with that URL. 这取决于您对该URL的处理方式。

When you just use a document.location = url, you don't want it encoded. 当您仅使用document.location = url时,就不需要对其进行编码。

If you plan on passing that URL as a variable, then yes you want it encoded or it will confuse the browser. 如果您打算将该URL作为变量传递,则可以,您希望对其进行编码,否则会混淆浏览器。 For instance: 例如:

http://www.someurl.com?myFavwebsite=http://www.stackoverflow.com?someParam=test . http://www.someurl.com?myFavwebsite=http://www.stackoverflow.com?someParam=test

See how that could be confusing to the browser? 看看这可能会使浏览器感到困惑吗?

By the way, never use a space in a url or php file. 顺便说一句,切勿在url或php文件中使用空格。 i've always found that to cause unnecessary stress. 我总是发现这会造成不必要的压力。 :) :)

Only a limited number of characters are allowed in URLs, according to the RFC 3986 standard. 根据RFC 3986标准,URL中仅允许使用有限数量的字符。 If you have a space in a URL, for example, this will make the URL invalid unless you encode it. 例如,如果URL中有空格,除非对URL进行编码,否则这将使URL无效。

Often, browsers can deal with URLs that are not properly encoded by doing the encoding themselves, but that's not something you should rely on as a web developer. 通常,浏览器可以通过自己进行编码来处理未正确编码的URL,但是作为Web开发人员,这不是您应该依靠的。

URL encoding is also critical when using URLs as parameters of another URL. 当使用URL作为另一个URL的参数时,URL编码也很关键。 In this case the reserved characters of the URL need to be encoded, not just the non-permitted characters. 在这种情况下,URL的保留字符需要进行编码,而不仅仅是非许可字符。 For this, however, you don't use encodeURI , but encodeURIComponent . 但是,为此,您不使用encodeURI ,而是使用encodeURIComponent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM