Cómo agregar un botón "Me gusta" de Facebook a una página impulsada por AJAX


He arrastrado la red y el Desbordamiento de la Pila y no he encontrado una respuesta adecuada a esta pregunta. Antes de comenzar el proceso de prueba y error de encontrar mi propia solución, pensé en recurrir a la confianza en el Cerebro de Desbordamiento de Pila y ver si ya había una implementación exitosa.

Tengo una página AJAX que se degrada correctamente para navegadores que no son javascript y SEO. Cada clic en la versión AJAX puede ser representado por una URL única.

Lo que quiero hacer es cambia dinámicamente el HREF del botón. Entiendo que esta etiqueta se convierte a HTML estándar en tiempo de ejecución (es decir, en un diseño de tabla / iframe desagradable).

Me preguntaba si alguien tenía alguna idea de cómo implementar este botón FB like en páginas AJAX?

Saludos por adelantado:)

EDITAR:

¿Qué piensas de este método que acabo de hackear juntos? ¿Ves algún gran problema con él?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="JS/jquery/jquery.js" type="text/javascript"></script>
    <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>

    <script language="javascript" type="text/javascript">
        $("document").ready
        (
            function ()
            {
                CreateNewLikeButton("http://www.yahoo.com")

                $("a#ChangeToGoogle").click
                (
                    function (e)
                    {
                        e.preventDefault();
                        CreateNewLikeButton("http://www.google.ca")
                    }
                );

            }
        );

        function CreateNewLikeButton(url)
        {
            var elem = $(document.createElement("fb:like"));
            elem.attr("href", url);
            $("div#Container").empty().append(elem);
            FB.XFBML.parse($("div#Container").get(0));
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <a id="ChangeToGoogle" href="#">Change To Google</a>
    <div id="Container">
        <fb:like href="http://www.NEVER_LINK_TO_THIS_12345.com"></fb:like>
    </div>
    </form>
</body>

</html>
Author: stef, 2010-11-19

7 answers

SOLUCIÓN SIMPLE

Just parse activa la función parse cuando se complete la carga.

Si está utilizando jQuery, hay una solución muy fácil y hábil para este problema:

$(document).ajaxComplete(function(){
    try{
        FB.XFBML.parse(); 
    }catch(ex){}
});

Http://developers.facebook.com/docs/reference/plugins/like /

 135
Author: Zorox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-17 22:14:56

Esta es la solución con la que terminé yendo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="JS/jquery/jquery.js" type="text/javascript"></script>
    <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>

    <script language="javascript" type="text/javascript">
        $("document").ready
        (
            function ()
            {
                CreateNewLikeButton("http://www.yahoo.com")

                $("#ChangeToGoogle").click
                (
                    function (e)
                    {
                        e.preventDefault();
                        CreateNewLikeButton("http://www.google.ca")
                    }
                );

            }
        );

        function CreateNewLikeButton(url)
        {
            var elem = $(document.createElement("fb:like"));
            elem.attr("href", url);
            $("#Container").empty().append(elem);
            FB.XFBML.parse($("#Container").get(0));
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <a id="ChangeToGoogle" href="#">Change To Google</a>
    <div id="Container">
        <fb:like href="http://www.NEVER_LINK_TO_THIS_12345.com"></fb:like>
    </div>
    </form>
</body>

</html>
 23
Author: nokturnal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-21 19:03:04

Estás haciendo esto difícil para ti mismo - solo renderiza uno nuevo basado en iframe.

<html>
<head>
  <title>Test Page</title>

  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript">  

  $(function()
  {
    $( '#ChangeToGoogle' ).click( function( event )
    {
      event.preventDefault();

      $( '#Container' ).empty().append( $('<iframe />')
        .attr( 'src', 'http://www.facebook.com/plugins/like.php?href=www.google.com&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' )
        .attr( 'scrolling', 'no' )
        .attr( 'frameborder', 'no' )
        .attr( 'style', 'border:none; overflow:hidden; width:450px; height:80px;' )
        .attr( 'allowTransparency', 'true' )        
      );            
    });
  });

  </script>
</head>

<body>
    <form id="form1" runat="server">
    <a id="ChangeToGoogle" href="#">Change To Google</a>
    <div id="Container">
      <iframe src="http://www.facebook.com/plugins/like.php?href=www.yahoo.com&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80"
        scrolling="no" frameborder="0"
        style="border:none; overflow:hidden; width:450px; height:80px;"
        allowTransparency="true">
      </iframe>
    </div>
    </form>
</body>

 2
Author: Peter Bailey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-18 22:23:57

Así es como manejé esta situación cuando me encontré con ella - parece funcionar bien.

// Set Facebook Like Button with jQuery
setFBLikeButtons = function (container,url,send,layout,width,show_faces,font) {
  // Set Default Args
  if(!send) { send = "false"; }
  if(!layout) { layout = "button_count"; }
  if(!width) { width = "100"; }
  if(!show_faces) { show_faces = "false"; }
  if(!font) { font = "arial"; }

  $(container).empty(); // Remove current like button
  $(container).html('<fb:like href="'+url+'" send="'+send+'" 
       layout="'+layout+'" width="'+width+'" show_faces="'+show_faces+'" 
       font="'+font+'"></fb:like>');
  FB.XFBML.parse(); // This is the magical syrup
}
 2
Author: rycaps,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-16 11:48:37

Crear botón me gusta

<head>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script>
window.onload = function(){
var divs = document.getElementsByTagName("span");
for(var i=0; i<divs.length i++){
if(divs[i].className == "likes"){
if(divs[i].title){ var Href = divs[i].title; }else{ var Href = window.location; }
var fb_like = document.createElement("fb:like");
fb_like.setAttribute("href", Href);
fb_like.setAttribute("layout", "box_count");
fb_like.setAttribute("show_faces", "false");
fb_like.setAttribute("width", "55");
document.getElementById("likes2").appendChild(fb_like);
}
}
}
</script>
</head>
<body>
<span class="likes" title="www.bzzs.me"></span>
</body>
 0
Author: Csáky Attila,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-29 06:28:11

Cárgalo después de que se cargue la ventana, esto es lo que funciona para mí:

$(window).load(function(){
     $.getScript('http://connect.facebook.net/en_US/all.js', function() {
          try{
                FB.XFBML.parse();
            } catch(ex) {}
      });
});
 0
Author: Devin Walker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-29 22:02:40

Si está utilizando el jQuery Mobile framework puede ejecutar el mismo código que la respuesta aceptada en el evento pagecontainershow que jQuery Mobile utiliza cuando muestra una nueva página.

// initialize new pages
$(document).on("pagecontainershow", (e, ui) =>
{
    try
    {
        FB.XFBML.parse();
    } catch (ex) { }
});
 0
Author: Simon_Weaver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-31 20:42:24