我想使用以下代码使用 javascript 重定向页面:
var s = 'http://blahblah/' + encodeURIComponent(something);
alert(s);
window.location.href = s;
警报显示正确的编码网址,但当我将其传递给 window.locaion.href 时,它会将页面重定向到错误的未编码网址。我怎样才能正确地做到这一点?谢谢
这可能
与(a)使用Firefox或(b)你输入encodedComponent
的特定API有关,比如谷歌搜索。
这是一个在Firefox-stable上经过测试的解决方案:
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
,因此您可以保存一些字母。 ;)