Render 'like' button after ajax call

前端 未结 2 1880
天命终不由人
天命终不由人 2021-01-31 10:48

there were a few question similar to mine on the stack but none that answered my question, so...

An ajax call returns the standard html code for creating the like button

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 11:22

    Not sure anyone needs it, but my complete code looks like this now and renders both FB page and Like button appropriatelly (LikeLink button created with material icon):

    
    
    var fbloaded = false; // if SDK is loaded, no need to do it again (though cache should do this?
    var fbpageid = "myPageId"; // FB page id
    
    // ajax call to FB SDK script
    if (!fbloaded) {
        $.ajax({
            type: "GET",
            url: "//connect.facebook.net/en_US/sdk.js",
            dataType: "script",
            cache: true,
            success: function () {
                fbloaded = true;
                FB.init({
                    appId: '{myAppId}',
                    version: 'v2.3' // or v2.0, v2.1, v2.0
                });
    // parse button after success
                FB.XFBML.parse();
            }
        });
    }
    
    var FBDivAppended = false; // if already done, do not call and render again
    PostUrl = window.location.href; // like button needs this... or not :)
    
    // when LikeLink is clicked, add the divs needed and at the end fire the FB script ajax call (resetFB)
    
    $("#LikeLink").click(function () {
    if (!FBDivAppended) {
                var $pagediv = $("
    "); var $fblikediv = $("
    "); var $fbdiv = $("
    "); var $fbroot = $("
    "); $fbdiv.append($pagediv).append($fblikediv); $(".Header").append($fbdiv).append($fbroot); FBDivAppended = true; } resetFB(); }

提交回复
热议问题