将特殊字符传递给mailto正文会炸毁JavaScript

时间:2011-11-07 08:22:16

标签: javascript jquery html mailto

我有一个C#ASP.NET应用程序,它为某些用户配置文件信息创建了一个JavaScript数组值。客户端,我使用jQuery / JavaScript读取数组并生成mailto链接。某些字段可以包含特殊字符,例如' & = / \ "

这是C#代码:

private String generateElementsArray(){
  StringBuilder sb = new StringBuilder();
  sb.Append("var currentElements = { currentUserName: '");
  sb.Append(currentUserName);
  sb.Append("', currentUserEmail: '");
  sb.Append(currentUserEmail);
  sb.Append("', currentSite: '");
  sb.Append(currentSite);
  sb.Append("', currentTitle: '");
  sb.Append(currentTitle);
  sb.Append("'}");
  return sb.ToString();
}    

我将上述方法的值写入页面,生成此JavaScript:

<script type="text/javascript">var currentElements = { currentUserName: 'Alex', currentUserEmail: 'myemailID', currentSite: 'Helpdesk', currentTitle: 'Phone User Guides & Troubleshooting'}</script>

然后我使用此JavaScript代码生成电子邮件链接,将锚标记附加到页面上的元素:

function generateEmailTo(){
  var body = currentElements.currentUserName + ' has shared a page with you on the intranet.%0A%0APage Title: %22' +
    currentElements.currentTitle.replace("&","and")  + '%22%0A' + $(location).attr('href').replace('#',''); 
  var subject = currentElements.currentUserName + ' has shared a page with you on the intranet';
  var mailto = 'mailto: ?body=' + body + '&subject=' + subject;
  var anchor = '<a href="' + mailto + '"></a>';

  $("#email-placeholder").wrap(anchor);
}
....

<img id="email-placeholder" title="Send this page to a friend." src="<%= baseUrl %>/SiteAssets/media/icons/email-icon.gif"/>

对于mailto正文,我注意到它只需要一小部分编码字符,例如%22表示双引号,%0A表示换行符。如何将单引号,&符号等特殊字符传递给mailto正文文本并保持JavaScript快乐?

1 个答案:

答案 0 :(得分:9)

Mailto是一种URI方案,因此其所有组件都必须进行URI编码。您可以使用JavaScript encodeURIComponent函数对mailto组件进行编码。请参阅以下示例:

function buildMailTo(address, subject, body) {
    var strMail = 'mailto:' + encodeURIComponent(address)
                   + '?subject=' + encodeURIComponent(subject)
                   + '&body=' + encodeURIComponent(body);
    return strMail;
}
var strTest = buildMailTo('abc@xyz.com', 'Foo&foo', 'Bar\nBar');
/* strTest should be "mailto:abc%40xyz.com?subject=Foo%26foo&body=Bar%0ABar" */
window.open(strTest);

希望得到这个帮助。