简体   繁体   中英

Encoding json data for a mailto link

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?

Here is a simple example:

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:

链接

Here is a JSBin showing what I am talking about:

https://jsbin.com/vuweyemeji/1/edit?html,js,output

Edit: 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.

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.

Try this:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM