Javascript Firefox自动解码url中的编码参数,在IE中不会发生

Javascript Firefox自动解码url中的编码参数,在IE中不会发生,javascript,ajax,encoding,encodeuricomponent,Javascript,Ajax,Encoding,Encodeuricomponent,我在Firefox和IE之间遇到了挫折,主要是Firefox,因为它在我使用Javascript之前会自动解码散列中的一个参数。IE不会自动解码url,因此不会给我阅读错误 我的问题与此类似,只是我没有使用ASP.NET 所以如果我使用像example.com/#question=!%这样的url40%23%24%25^%26*( 而“!%40%23%24%25^%26*”是使用encodeURIComponent编码的,在IE中,当我访问哈希时,它将保留为“!%40%23%24%25^%26*

我在Firefox和IE之间遇到了挫折,主要是Firefox,因为它在我使用Javascript之前会自动解码散列中的一个参数。IE不会自动解码url,因此不会给我阅读错误

我的问题与此类似,只是我没有使用ASP.NET

所以如果我使用像
example.com/#question=!%这样的url40%23%24%25^%26*(

而“!%40%23%24%25^%26*”是使用encodeURIComponent编码的,在IE中,当我访问哈希时,它将保留为“!%40%23%24%25^%26*”,而在firefox中,当我访问哈希时,它会自动解码为“!@$%^&*”

问题是,在我的脚本中,我使用decodeURIComponent对编码的值进行解码,如果字符串确实进行了编码,这就可以了。因为它已经在Firefox中解码,它会给我一个格式错误的URI序列错误,IE根本不会给我任何错误


如何解决此问题?

搜索后,我发现这是一个跨浏览器问题,最好使用
location.href.split(“#”)而不是
window.location.hash
这实际上是您想要使用的:

decodeURI(window.location.hash.substr(1))

事实上,window.location.href.split(“#!”)[1]不会被FF自动解码(至少今天是这样)。

上述答案有效,但url包含多个#的情况除外。这应能处理所有情况:

var hash = "";
var indexOfHash = location.href.indexOf("#");
if (indexOfHash > -1) {
    hash = location.href.substring(indexOfHash);
}
而且,这似乎应该很快在Firefox中得到修复。只需点击夜间睡眠:


我遇到了这个问题。我用这个解决方案解决了它:

var currentLocation = document.location.hash;
var decodedLocation = decodeURI(currentLocation);

这是一个非常古老的问题,但根本的问题仍然没有解决。Firefox编码了其他浏览器没有的东西

出于挫败感,我不得不创建一种完全不同的方法,实际上使算法独立于字符串是否编码

我希望这个解决方案能找到需要它的人:

function encodeOnce(text) {
  var doubleEncoded = encodeURIComponent(text);
  // only dive into it if there are any encoded strings...
  if (doubleEncoded.indexOf('%') != -1) {
    // reverse replace all % signs
    doubleEncoded = doubleEncoded.replace(/%25/g, '%');
    // if this is not equal to the original string, ...
    if (doubleEncoded != text) {
      // ... that means there was something to encode
      text = doubleEncoded;
    }
  }
  return text;
}
那么你可以这样做:

solution = encodeOnce(window.location.hash.slice(1));

你觉得怎么样?

非常感谢。我刚刚在Fx(Chrome很好)和location.href.split(“#!”)[1]中遇到了同样的问题。Firefox似乎也不会很快解决这个问题。他们从2002年开始讨论这个问题:(Firefox允许“#”在散列字符串内部,所以so
window.location.hash.split(“#”).splice(1.join(“#”)
window.location.hash实际上是问题的根源,所以这不起作用。但它应该是这样的。。。