使用jquery加载gravatar

只是想在博客上创建一个简单的评论表单。 我想在他/她在电子邮箱中写入时加载用户的gravatar(使用jQuery)。

我怎样才能做到这一点?

gravatar url看起来像这样:

http://www.gravatar.com/avatar/ 

以下是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 = $('').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,则最好在服务器上对电子邮件进行编码,以便在查看源时,用户电子邮件不会公开显示。

看看我提供function的小提琴

 get_gravatar_image_url (email, size, default_image, allowed_rating, force_default) 

仅提供电子邮件是必需的 – 其余使用默认值。

一定要包括Joseph Myers的事实上标准的MD5生成器JS文件

  

哇感谢这篇文章。 但是,如果你有自己的空白图像,你想使用它而不是gravatar。

    

棘手的部分是使用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设置一个image src属性,如下所示:

 var email = "someone@example.com"; $("#image").attr("src", gravatar(email)); 
Interesting Posts