2014-02-21 18 views
3

我想用下面的代碼重定向與JavaScript的網頁:的Javascript傳遞一個網址編碼window.location.href

var s = 'http://blahblah/' + encodeURIComponent(something); 
    alert(s); 
    window.location.href = s; 

警報顯示正確編碼的URL,但是當我將它傳遞給窗口.locaion.href,它將頁面重定向到未編碼的url,這是錯誤的。 我怎麼能正確地做到這一點? 感謝

+0

它在我身邊正常工作。 –

+0

對我來說,Chrome瀏覽器沒問題,但沒有Firefox。 – Needpoule

+0

對我來說,它在兩個瀏覽器中都可以工作。 –

回答

3

這可能與(a)使用Firefox或(b)該你喂encodedComponent到,像谷歌搜索特定的API。

這裏是在Firefox上穩定的一個測試的解決方案:

var clearComponent = 'flowers for my boyfriend & husband on valentines'; 
var encodedComponent = encodeURIComponent(clearComponent); 
var googleSafeComponent = encodedComponent.replace(/%20/g,'+'); // replaces spaces with plus signs for Google and similar APIs 
var completeURI = 'http://google.com/?q=' + googleSafeComponent; 
window.location = completeURI; 

或全部一行:

window.location = 'http://google.com/?q=' + encodeURIComponent('flowers for my boyfriend & husband on valentines').replace(/%20/g,'+'); 

window.location意味着window.location.href這樣你就可以節省一些字母。 ;)