为mailto链接编码json数据 [英] Encoding json data for a mailto link
问题描述
如何正确地在查询参数中对带有JSON数据的mailto链接进行编码,以便当某些JSON数据可能包含空格时,该链接能够按预期工作?
How do I properly encode a mailto link with JSON data in the query parameters so that the link works as expected when some of the JSON data possibly includes spaces?
这是一个简单的例子:
var data = {
"Test": "Property with spaces"
};
var mailTo = 'mailto:?body=http://www.google.com/?body=' + JSON.stringify(data);
document.getElementById("link").href = mailTo;
单击链接后,电子邮件中的结果链接如下所示:
The resulting link in the email after clicking the link looks like this:
这是一个JSBin,显示我在说什么:
Here is a JSBin showing what I am talking about:
https://jsbin.com/vuweyemeji/1/edit?html ,js,输出
对我来说,添加encodeURI()或encodeURIComponent()似乎不起作用.我尝试在数据对象周围添加这两种方法,当我单击mailto链接时,URL在Outlook中仍然看起来相同.
Adding encodeURI() or encodeURIComponent() doesn't seem to work for me. I tried adding either of those methods around the data object and when I click the mailto link the url still looks the same in outlook.
推荐答案
You need to use encodeURIComponent
twice, because you are encoding a parameter inside another parameter.
您的链接正在使用mailto
协议,并使用了body
参数,应该对内容进行编码.但是,在该内容内,您输入的是带有参数的URL,因此,也应该对这些参数进行编码.
Your link is using the mailto
protocol and using a body
parameter which content should be encoded. But, inside that content you are entering a URL which has parameters, so, this parameters should be encoded also.
尝试一下:
var data = {"Test": "Property with spaces"};
var mailTo = 'mailto:?body=' + encodeURIComponent('http://www.google.com/?body=' + encodeURIComponent(JSON.stringify(data)));
document.getElementById("link").href = mailTo;
<a id='link'>anchor</a>
这篇关于为mailto链接编码json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!