簡體   English   中英

帶有空格和%的Javascript window.open url

[英]Javascript window.open url with spaces and %

我正在嘗試使用帶空格的url 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);

運行此代碼將打開一個新窗口,其中包含http://twitter.com/share?text=Hello,%2520world!&url=http://yoursite.com

會發生什么是msg中的空格轉換為%20,然后'%'轉換為%25。 作為一種解決方法,我補充說:

msg = msg.replace(/\\s/g, '+');

但是我需要注意其他字符還是有更好的解決方法?

試試這個:

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); 

請注意不同的Twitter網址和查詢字符串參數的編碼。

你必須編碼URL。

URL中不能有任何空格。

因此,瀏覽器會根據需要重新解釋網址空間,除非您確切地告訴它如何:

var msg = 'Hello,%20world!';

我有同樣的問題。 似乎如果您使用網址http://www.twitter.com您的msg會被轉義兩次。 如果你看一下twitters dev頁面 ,他們會使用https://twitter.com

對於您的代碼,請刪除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);

您甚至不需要在消息上使用encodeURI或escape。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM