Loading gravatar using jquery

2019-03-09 02:26发布

Just trying to crate a simple comment form on a blog. I want to load the user's gravatar (using jQuery) when he/she writes this in the email box.

How can I do that?

4条回答
冷血范
2楼-- · 2019-03-09 02:38

Wow thanks for this post. But if in case you have your own blank image and you want to use it instead of the gravatar.

<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>
查看更多
Summer. ? 凉城
3楼-- · 2019-03-09 02:44

The gravatar url looks like this:

http://www.gravatar.com/avatar/<md5hashofemail>

Here are the rest of the options for the URL.

So all you're going to have to do is include a function called md5 that returns the md5 hash of the user's email. There are many online that do this, but I believe https://github.com/blueimp/JavaScript-MD5/blob/master/README.md works well. After that, just do:

// 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));

I thought this was obvious, but I will add it for posterity's sake:

If user emails are private and you're showing this ala-stackoverflow in a listing, you are probably better off encoding the email on the server so that user emails are not publicly visible if you look at the source.

查看更多
叛逆
4楼-- · 2019-03-09 02:46

check out my fiddle providing the function

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

Only providing the email is mandatory - the rest uses default values.

Be sure to also include the de-facto-standard MD5-generator JS file from Joseph Myers with

<script src="http://www.myersdaily.org/joseph/javascript/md5.js"></script>
查看更多
闹够了就滚
5楼-- · 2019-03-09 02:58

The tricky part is generating the URL using an MD5 hash implementation, which is separate from jQuery. I found that the blueimp-md5 library has the most stars of the various MD5 packages on GitHub, and it's pretty much self-contained (about 6kb minified). If you are using Node and/or Browserify, this solution might work well for you:

var md5 = require("blueimp-md5");
function gravatar(email){
  var base = "http://www.gravatar.com/avatar/";
  var hash = md5(email.trim().toLowerCase());
  return base + hash;
}

Then you can set an image src attribute using jQuery like this:

var email = "someone@example.com";
$("#image").attr("src", gravatar(email));
查看更多
登录 后发表回答