试图在博客上创建一个简单的评论表单。我想在他/她在电子邮箱中写入时加载用户的gravatar(使用jQuery)。
我该怎么做?
答案 0 :(得分:51)
gravatar url看起来像这样:
http://www.gravatar.com/avatar/<md5hashofemail>
Here are the rest of the options for the URL.
所以你要做的就是包含一个名为md5的函数,它返回用户电子邮件的md5哈希值。网上有很多人这样做,但我相信https://github.com/blueimp/JavaScript-MD5/blob/master/README.md效果很好。之后,就这样做:
// get the email
var email = $('#email').val();
// -- maybe validate the email?
// create a new image with the src pointing to the user's gravatar
var gravatar = $('<img>').attr({src: 'http://www.gravatar.com/avatar/' + md5(email)});
// append this new image to some div, or whatever
$('#my_whatever').append(gravatar);
// OR, simply modify the source of an image already on the page
$('#image').attr('src', 'http://www.gravatar.com/avatar/' + md5(email));
我认为这很明显,但我会为了后人的缘故加上它:
如果用户的电子邮件是私有的,并且您在列表中显示了这个ala-stackoverflow,那么最好不要在服务器上对电子邮件进行编码,以便在查看源代码时用户电子邮件不会公开显示。
答案 1 :(得分:4)
查看提供功能的my fiddle
get_gravatar_image_url (email, size, default_image, allowed_rating, force_default)
仅提供电子邮件是强制性的 - 其余部分使用默认值。
请务必同时附上Joseph Myers的事实标准MD5-generator JS file
<script src="http://www.myersdaily.org/joseph/javascript/md5.js"></script>
答案 2 :(得分:1)
<script src="md5.js"></script>
<img id="image" src="images/mydefault.png" />
<script>
var src = 'http://www.gravatar.com/avatar/' +
md5('yourmail@gmail.com') + '?default=' + encodeURIComponent(GetRootDomain() + '/Content/images/nopic-small.png');
$('#image').attr('src', src);
</script>
答案 3 :(得分:0)
棘手的部分是使用MD5哈希实现生成URL,该实现与jQuery分开。我发现blueimp-md5库在GitHub上拥有各种MD5包中最多的星星,并且它几乎是独立的(大约6kb缩小)。如果您使用的是Node和/或Browserify,此解决方案可能适合您:
var md5 = require("blueimp-md5");
function gravatar(email){
var base = "http://www.gravatar.com/avatar/";
var hash = md5(email.trim().toLowerCase());
return base + hash;
}
然后您可以使用jQuery设置图像src
属性,如下所示:
var email = "someone@example.com";
$("#image").attr("src", gravatar(email));