一.JavaScript获取url信息
alert("location:"+window.location);
alert("href: "+window.location.href);
alert("protocol: "+window.location.protocol);
alert("host&port: "+window.location.host);
alert("port: "+window.location.port);
alert("hostname: "+window.location.hostname);
二.AngularJS通过$location获取及改变当前页面的URL
下面获取与修改的URL以 ‘http://172.16.0.88:8100/#/homePage?id=10&a=100' 这个路径为例。
1.获取url的相关方法(不修改URL)
a.获取当前完整的url路径
var absurl = $location.absUrl();
//http://172.16.0.88:8100/#/homePage?id=10&a=100
b. 获取当前url路径(当前url#后面的内容,包括参数和哈希值):
var url = $location.url();
// 结果:/homePage?id=10&a=100
c. 获取当前url的子路径(也就是当前url#后面的内容,不包括参数)
var pathUrl = $location.path()
//结果:/homePage
d.获取当前url的协议(比如http,https)
var protocol = $location.protocol();
//结果:http
e.获取主机名
var localhost = $location.host();
//结果:172.16.0.88
f.获取当前url的端口
var port = $location.port();
//结果:8100
g.获取当前url的哈希值
var hash = $location.hash()
//结果:http://172.16.088
h.获取当前url的参数的序列化json对象
var search = $location.search();
//结果:{id: "10", a: "100"}
2.修改url的相关方法(改变URL相关内容)
a.修改url的子路径部分(也就是当前url#后面的内容,不包括参数):
$location.url('/validation');
//结果:http://172.16.0.88:8100/#/validation
b.修改url的哈希值部分
$location.hash('myhash3');
//结果:http://172.16.0.88:8100/#/homePage?id=10&a=100#myhash3
c.修改url的参数部分(第一个参数表示url参数的属性名,第二个参数是该属性名的属性值,如果是已有属性名,则修改,如果不是已有属性,则新增)
$location.search('id','111')
// 结果(修改参数值):http://172.16.0.88:8100/#/homePage?id=111&a=100
$location.search('ids','111')
// 结果(新增ids参数): http://172.16.0.88:8100/#/homePage?id=111&a=100&ids=111
d.一次性修改多个参数
$location.search({id:'55','a':'66'})
//结果:http://172.16.0.88:8100/#/homePage?id=55&a=66#myhash3
e.第一个值表示url参数的属性名,如果是已有属性名,则删除该属性,如果不是已有属性,那就等于没改过
$location.search('age',null)
3.修改URL但不存入历史记录
在上面的修改url的方法的时候,每修改一次,url都会被存入历史记录,可以使用后退按钮回到修改前的url,如果不想要这种效果,而仅仅是替换当前的记录,可以使用 $location.path('/validation').replace();