2011-01-29 31 views
14

我在Firefox和IE之間感到沮喪,主要是Firefox,因爲它會自動解碼散列中的參數,然後才能在Javascript中使用它。 IE不會自動解碼網址,因此不會給我閱讀錯誤。除了我,如果我拿一樣example.com/#question=!%40%23%24%25^%26*(Firefox自動解碼URL中的編碼參數,不會發生在IE中

而「!%40%23%24%25 ^%的URL我不使用ASP.NET ASP.NET MVC automatically decoding JSON-encoded parameters from AJAX

所以

我的問題是與此類似26 *(「使用encodeURIComponent進行編碼,在IE中,當我訪問哈希時,它將被保留爲」!%40%23%24%25 ^%26 *(「,但是在firefox中,當我訪問哈希時它會自動解碼爲「!@#$%^ & *(」

這個問題是,在我的腳本中,我使用decodeURIComponent來解碼編碼值,w如果字符串確實被編碼了,那很好。由於它已經在Firefox中解碼,它給了我一個格式不正確的URI序列錯誤,IE並沒有給我任何錯誤。

我該如何解決這個問題?

回答

19

搜索後,我發現,這是一個跨瀏覽器的問題,最好是使用location.href.split("#")[1]代替window.location.hash

+0

非常感謝。我剛剛在Fx中遇到了同樣的問題(Chrome很好),而location.href.split(「#!」)[1]也適用於我。 – meloncholy 2011-05-11 13:08:59

+1

似乎Firefox不會很快解決這個問題。自2002年以來他們一直在討論這個錯誤:(https://bugzilla.mozilla.org/show_bug.cgi?id = 135309和https://bugzilla.mozilla.org/show_bug.cgi?id=483304 – gregers 2014-05-12 09:57:29

1

這實際上是你想要的內容:

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

事實上窗口。 location.href.split(「#!」)[1]不會被FF自動解碼(至少今天)。

0

上面的答案除了你的url包含多個#的情況外。這應該處理所有情況:

var hash = ""; 
var indexOfHash = location.href.indexOf("#"); 
if (indexOfHash > -1) { 
    hash = location.href.substring(indexOfHash); 
} 

此外,它似乎應該在Firefox很快修復。只要按下Nightlies版:

https://bugzilla.mozilla.org/show_bug.cgi?id=378962

0

我有這個問題。我解決了這個解決方案:

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

這是一個非常古老的問題,但潛在的問題仍然沒有解決。 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)); 

你覺得呢?