Loading gravatar using jquery

前端 未结 4 786
轮回少年
轮回少年 2021-01-31 18:31

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条回答
  •  自闭症患者
    2021-01-31 19:02

    The gravatar url looks like this:

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

    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 = $('').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.

提交回复
热议问题