繁体   English   中英

当推入window.location.hash时,正确编码的字符串会被解码

[英]Correctly encoded string gets decoded when pushed into window.location.hash

目标:正确地将data属性中的字符串放入window.location.hash

代码:

map = {path: $(this).attr('data-path'), rev: $(this).attr('data-rev')};
window.location.hash = getMapParams(map);

function getMapParams(map) {
  s="";
  for(key in map) {
    value=eval("map."+key);
    if (s.length > 0) {
      s+="&";
    }
    s+=encodeURIComponent(key)+"="+encodeURIComponent(value);
  }
  return s;
}

问题:只要data-path属性包含空格,Firefox就无法正确放入哈希。 该空间将显示为未编码,而在其他浏览器中,它正确编码为%20

奇怪的怪癖:如果我调试代码,字符串将编码空间一起列出。

研究完成:我已经找到了很多解决方案来正确读取 Firefox中的哈希值。 以这种或那种方式,我的代码工作正常。

问题:如何阻止Firefox对我放入window.location.hash的字符串中的空格进行urldecoding

我经常试图避免使用window.location.hash因为它在浏览器中并不统一。

因此,而不是做以下

window.location.hash = "some hash value";

我会做

window.location.href = window.location.href.split("#")[0] + "#" + encodeURIComponent("some hash value");

此外,虽然Firefox在地址栏中显示解码的哈希值(即''而不是%20),但如果您尝试复制地址,则实际编码。 因此,显示的内容不是URI中的内容。

顺便说一句,我总是使用以下代码访问哈希

var hash_val = window.location.href.split("#")[1] || "";

暂无
暂无

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

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