将编码的URL传递给window.location.href的Javascript方法

9

我想使用以下代码通过JavaScript重定向页面:

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

这个警告显示了正确编码的URL,但是当我将它传递给window.locaion.href时,它会将页面重定向到错误的未编码URL。 我该怎么做才能正确地操作呢? 谢谢。


在我的端上运行良好。 - Suman Bogati
对我来说,使用Chrome没问题,但使用Firefox就不行。 - Needpoule
对我来说,在两个浏览器中都可以正常工作。 - Suman Bogati
1
实际上它在两个浏览器上都可以工作。但是Firefox会在URL栏中显示未编码的URL。 - Needpoule
听起来像是版本问题!出于兴趣,你能告诉我们哪些浏览器的哪个版本对你不起作用吗? - taddy hoops
1个回答

6
这可能与使用Firefox浏览器或传入特定API(如Google搜索)中的encodedComponent有关。以下是已测试的适用于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,因此可以省略一些字母。 ;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接