【问题标题】:Follow button with AJAX使用 AJAX 的跟随按钮
【发布时间】:2015-09-01 10:56:32
【问题描述】:

我创建了一个按钮,您可以使用 AJAx 和 PHP 来关注/取消关注用户。 如果你点击按钮,你关注,否则,你取消关注。 有一个功能可以检查您尝试关注的用户是否已被关注...

HTML

<div class="heart"><i class="fa fa-heart awesome"></i></div>

PHP

    public static function Follow($user, $seguidor){
        $sql = "INSERT INTO seguidores (id_canal, id_seguidor) VALUES ('$user', '$seguidor')";
        $resultado = self::Conexion($sql);
        return $resultado;
    }

    public static function CheckFollow($user, $seguidor){
        $heart = "";
        $sql = "SELECT * FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
        $resultado = self::Conexion($sql);
        $verificacion = false;

        if(isset($resultado)) {
            $fila = $resultado->fetch();
            if($fila !== false){
                $verificacion = true;
            }
        }

        if($verificacion == false){
            $heart = "<div data-id='".$user."' class='heart'><i class='fa fa-heart awesome'></i></div>";
        } else {
            $heart = "<div data-id='".$user."' class='heart like'><i class='fa fa-heart awesome'></i></div>";
        }
        return $heart;
    }

    public static function Unfollow($user, $seguidor){
        $sql = "DELETE FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
        $resultado = self::Conexion($sql);
        return $resultado;
    }

AJAX

$(document).ready(function () {

    $function() {
        var element = $(this);
        var data_id = element.attr("data-id");

        $.ajax({
            type: "POST",
            url: "database.php",
            data: data_id,
            success: function(){ }
        });
        return false;
    }
});

问题是,我每次点击按钮时如何加载那些 php 函数...

点击 > 关注

再次点击 > 取消关注

【问题讨论】:

  • 看看为登录用户创建关注取消关注功能,如果用户关注某人然后隐藏关注按钮并为该特定登录用户显示取消关注按钮。
  • 这不是我想要的方式:S。当您关注某人时,.heart 会收到另一个名为 .like 的类,然后,div 变为橙色,否则变为黑色......

标签: php ajax


【解决方案1】:

这里有一些建议:

我注意到您正在 PHP 中创建 HTML 字符串。如果可能,您希望避免这样做。

保留您所有的 HTML、CSS 和 JavaScript 客户端。随着您作为开发人员的进步,您将开始了解原因。将它们视为模板。

在这种情况下,您只需将“已关注”或“未关注”返回给客户端回调。可以将其归结为布尔值!

因此,在您的模板中,定义关注状态和未关注状态。使用 CSS 隐藏适当的一个。这可以非常轻巧!

在这些示例中,您只需在按钮上设置关注属性。

所以你的 javascript 看起来像:

// I would do something like:
find=document;
id="getElementById";

/* ... */

success: function (request, status)
{   
    if (!status)
        return
    ;

    find[id]("follow-1").setAttribute("follow", request.responseText)
}

(检查lib的ajax api)

1.)

<button id="follow-1" follow="true">
 <img src="transparent.png" />
</button>

+

button[follow="false"] > img
{ background: transparent url("unfollow.png");
}
button[follow="true"] > img
{ background: transparent url("follow.png");
}

2.)

<button id="follow-1" follow="true">
 <img src="follow.png" />
 <img src="unfollow.png" />
</button>

+

button[follow] > img
{ display: none;
}
button[follow="false"] > img:last-child
{ display: block;
}
button[follow="true"] > img:first-child
{ display: block;
}

【讨论】:

    【解决方案2】:

    我建议使用诸如 CodeIgniter 之类的框架来处理后端,因为您可以直接从 ajax 将数据直接发布到公共控制器方法,但大致了解它是如何工作的(您可能需要修复错误/调整正如我凭记忆写的):

    添加到 PHP 以处理传入请求:

    //Minimal vulnerability protection while getting inputs.
    $update_types = array("Follow", "CheckFollow", "Unfollow");
    $update_method = in_array($_POST["update_type"], 
                            $update_types)? $_POST["update_type"], "");
    
    if ($update_method) {
        //Call the update function & bounce the response
        //in JSON back to the AJAX handler.
        echo json_encode(call_user_func($update_method, 
             (int) $_POST["user_id"], (int) $_POST["seguidor"]));
    }
    

    Javascript:

      $(document).ready(function () {
    
        //Button click handler.
        $("div.heart").on("click", function() {
           var my_button = $(this);
           var update_type = "";
    
           if (my_button.hasClass('.like'))
               update_type = "Unfollow";
           else
               update_type = "Follow";
    
           $.ajax({
               type: "POST",
               url: "database.php",
               data: {
                      "update_type": update_type,
                      user_id: my_button.attr("data-id"),
                      seguidor: "some value here - not sure based on code"
               },
               success: function(response) {   
                 //response from server - check for errors...
                 //Update the UI - add heart if follow updated, remove it if not.
                 //You will need to modify your php functions to return result code and then either add "like" class or remove it - obviously this is not a complete rewrite of your app.
                 if ("/* result is followed */")
                   my_button.addClass("like");
                 else
                    my_button.removeClass("like");
               }
           });
        });
    });
    

    【讨论】:

    • seguidor 是您关注某个频道的用户。该变量应该返回某人在关注某人时正在使用的会话中的值。
    • 这个答案是经过深思熟虑的,因为它具有切换的能力,除了一个简单的问题:默认情况下,按钮的原始状态是“不像”。只有单击一次,它才会切换,然后反映真实状态。我只需定义 1 个 ajax 方法并(1)在页面加载时调用它一次以显示正确的默认状态(2)在每次单击时调用它来稍微改变它。只需在情况 1 或 2 中使用 ajax 通过 POST 传递一个额外的布尔值来告诉服务器它是否应该切换;案例 1 是否/案例 2 始终是。
    • 但是,您仍然可以在您的答案中这样做,但前提是您在提供页面本身时让 PHP 动态填写按钮 html 上的默认“like”类。然而,由于“like/unlike”特性已经被认为是一种经常使用且在编程上微不足道的特性,因此在客户端使用 ajax 填充默认值是整体的全栈、少麻烦、直截了当的方法.
    猜你喜欢
    • 1970-01-01
    • 2022-06-27
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多