在请求的URL 路径中有些时候都会跟着一些参数,在处理逻辑的时候会用到,为了方便使用这些参数
使用js处理一下,机构就以对象结构形式,方便获取调用:
例如:
urlParam = {
id:”123456”,
name:”tom”
}
location方法:
如请求的整个路径:http://1.11.111.11:8080/locationtest/locationtest.html?id=1234&name=abcd#hash
参数说明:
对象方法:
location.host = “1.11.111.11:8080”;
(得到 URL 中的主机名称和端口号)
location.port = “8080”;
(得到URL中端口号)
location.hostname = “1.11.111.11”;
(得到URL中的主机名称)
location.href = “http://1.11.111.11:8080/locationtest/locationtest.html?id=1234&name=abcd“;
(获取整个URL路径)
location.search= “?id=1234&name=abcd”;
(设置或返回从问号 (?) 开始的 URL(查询部分))
location.pathname = “/locationtest/locationtest.html”;
(设置或返回URL 中的路径部分)
location.protocol = “http:”;
(设置或返回URL路径的协议)
location.origin = “http://1.11.111.11:8080“;
(设置或返回URL中的协议名称及主机名称、端口号)
location.hash = “#hash”;
(#代表网页中的一个位置。其右面的字符,就是该位置的标识符;#是用来指导浏览器动作的,在第一个#后面出现的任何字符,都会被浏览器解读为位置标识符。这意味着,这些字符都不会被发送到服务器端。比如颜色#ccc,如果想要将这个颜色值传到服务器需要将’#’由%23转义;)
对象属性:
location.reload();
(重新加载当前文档)
location.replace(“locationtest2.html”);
(以新的文档替换当前文档,替换后浏览器回退功能不会回退到之前的文档;注意参数值如果不加协议名称,如:location.replace(“www.baidu.com”);将不会跳转,会在当前文档的目录路径下去寻找”www.baidu.com”这个新文档,如果没有会404;修改成location.replace(“https://www.baidu.com/“);将会正确的替换到百度的首页面;)
首先通过 location.search方法获取地址栏中”?”之后的字符串,之后通过indexOf()方法和split()方法进行截取最后以对象形式保存。
完整代码:
function GetUrlParam() {
var url = location.search;
var thisParam = new Object();
// 判断是否存在请求的参数
if (url.indexOf("?") != -1) {
var str = url.substr(1);
// 截取所有请求的参数,以数组方式保存
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
// 获取该参数名称,值。其中值以unescape()方法解码,有些参数会加密
thisParam[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
// 返回改参数列表对象
return thisParam;
}