2014-02-21 19 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这样你就可以节省一些字母。 ;)