URL的 ? 和 # (hash),如何将参数保存在URL中,用于刷新获取之前的变量?

URL中会带上参数,假如是?开头的,那这个是会被加入到ajax请求中的,#(hash)相当于书签锚点,用于定位页面,不会加入到ajax请求中,所以有些时候,我们可以把一些参数放在#后面

如何获取URL中的参数并解析出来?

let url = location.search; //获取url中"?"符后的字串
let theRequest = new Object();
if (url.indexOf("?") != -1) {
  let str = url.substr(1);
  let strs = str.split("&");
  for(let i = 0; i < strs.length; i ++) {
    theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
  }
}
直接theRequest.name,就可以调用了;
 
如何设置、获取#后面的参数?
hash可读、可写,
写:window.location.hash = '.....'
读:window.location.hash
获取到string后,然后在进行解析,解析的办法可以参考上一条。
 
希望本文对你有所帮助
 
 

posted on 2019-07-30 19:58  王子乔  阅读(1670)  评论(0编辑  收藏  举报

导航