Javascript 将编码的 url 传递给 window.location.href

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21937353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:02:38  来源:igfitidea点击:

Javascript passing an encoded url to window.location.href

javascript

提问by user1213679

I'd like to redirect a page with javascript using the following code:

我想使用以下代码重定向带有 javascript 的页面:

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

The alert shows the correct encoded url but when I pass it to window.locaion.href, it redirects the page to the unencoded url which is wrong. How could I do it properly? Thanks

警报显示了正确的编码 url,但是当我将它传递给 window.locaion.href 时,它会将页面重定向到错误的未编码 url。我怎么能正确地做到这一点?谢谢

回答by Thomas Hughes

This could be related to (a) using firefox or (b) specific APIs that you're feeding encodedComponentinto, like Google search.

这可能与 (a) 使用 firefox 或 (b) 您输入的特定 API encodedComponent(例如 Google 搜索)有关。

Here's one tested solution on Firefox-stable:

这是一个在 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;

Or all in one line:

或者全部在一行中:

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

window.locationimplies window.location.hrefso you can save some letters. ;)

window.location暗示window.location.href所以你可以保存一些字母。;)