带有空格和 % 的 Javascript window.open url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5318628/
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
Javascript window.open url with spaces and %
提问by nymo
I'm trying window.open
with a url with spaces:
我正在尝试window.open
使用带空格的网址:
var msg = 'Hello, world!';
var url = 'http://yoursite.com';
var link = 'http://www.twitter.com/share?text=' + msg + '&url=' + url;
window.open(link);
Running this code will open a new window with http://twitter.com/share?text=Hello,%2520world!&url=http://yoursite.com
.
运行此代码将打开一个带有http://twitter.com/share?text=Hello,%2520world!&url=http://yoursite.com
.
What happens is that the space in msg is converted to %20, then the '%' is converted to %25. As a workaround, i added:
发生的情况是 msg 中的空格被转换为 %20,然后 '%' 被转换为 %25。作为一种解决方法,我补充说:
msg = msg.replace(/\s/g, '+');
msg = msg.replace(/\s/g, '+');
But are there other chars i need to watch out for or is there a better workaround?
但是还有其他我需要注意的字符还是有更好的解决方法?
回答by DTRx
Try this instead:
试试这个:
var msg = encodeURIComponent('Hello, world!');
var url = encodeURIComponent('http://www.google.com');
var link = 'http://twitter.com/intent/tweet?text=' + msg + '&url=' + url;
window.open(link);
Note the different Twitter url and the encoding of the query string params.
请注意不同的 Twitter url 和查询字符串参数的编码。
回答by Naftali aka Neal
you have to encode URLs.
你必须对 URL 进行编码。
There cannot be any spaces in the URL.
URL 中不能有任何空格。
Therefore the browser reinterprets the url spaces as it wants unless you tell it exactly how:
因此,浏览器会根据需要重新解释 url 空间,除非您确切地告诉它如何:
var msg = 'Hello,%20world!';
回答by vfranchi
I had the same problem. It seems that if you use the url http://www.twitter.com
your msg gets escaped twice. If you look at twitters dev page, they use https://twitter.com
.
我有同样的问题。似乎如果您使用 url,http://www.twitter.com
您的 msg 会被转义两次。如果您查看twitter 的开发页面,他们会使用https://twitter.com
.
For your code, remove the wwwand I think it's good to use httpsinstead of http
对于您的代码,请删除www,我认为使用https而不是http很好
var msg = 'Hello, world!';
var url = 'http://yoursite.com';
var link = 'https://twitter.com/share?text=' + msg + '&url=' + url;
window.open(link);
You don't even need to use encodeURI or escape on your message.
您甚至不需要在消息中使用 encodeURI 或转义。