URL组分

时间:2022-11-17 09:46:07

url通常包含多个组成部分,在js中可通过location对象获取其中各项信息

访问http://mp.weixin.qq.com/s?__biz=MjM5NjA0NjgyMA==&mid=2651061017&idx=1&sn=429701cec06841504f65aaccc2b5baf3&scene=0#wechat_redirect,在console执行代码:

for(var obj in location){console.log(obj+"  "+location[obj]);}

结果如下:

href  http://mp.weixin.qq.com/s?__biz=MjM5NjA0NjgyMA==&mid=2651061017&idx=1&sn=429701cec06841504f65aaccc2b5baf3&scene=0#wechat_redirect
origin http://mp.weixin.qq.com
protocol http:
host mp.weixin.qq.com
hostname mp.weixin.qq.com
port
pathname /s
hash #wechat_redirect
search ?__biz=MjM5NjA0NjgyMA==&mid=2651061017&idx=1&sn=429701cec06841504f65aaccc2b5baf3&scene=0 ancestorOrigins [object DOMStringList]
reload function reload() { [native code] }
replace function () { [native code] }
assign function () { [native code] }

所以一个完整地址通常由 协议+主机+端口+路径[+hash或search] 组成,其中hash和search是可选项、port默认为80值未列出

值得注意的是,浏览器层面可以后的hash值,但向服务器发起请求时hash值是不回带上的,即hash值对于服务端来说是不可见的。"hash is not sent in request to server."

实际上,前面示例中 的URL是web url,更一般的url格式(参阅:https://en.wikipedia.org/wiki/URL)为: URI = scheme:[//authority]path[?query][#fragment] ,其中 authority = [userinfo@]host[:port]

常用的schema: http, https, ftp, mailto, file, data, irc 等