JavaScript >> Javascript 文檔 >  >> Tags >> CSS

AJAX 點擊欣賞徽章

當您在線發佈內容時,沒有太多方法可以確定人們是否喜歡您所說的話。評論是博客的基石,要求太高,用戶往往不願發表評論。如果您去過 Behance,您可能已經註意到他們的欣賞徽章 ,這是對這個確切問題的巧妙解決方案。人們通過它分享他們對某人工作的欣賞。

今天我們正在實現這樣一個徽章,您可以通過一點 jQuery 魔術將其包含在您網站的每個頁面中。所以繼續從上面的按鈕下載 zip(包括 PSD! ) 並繼續教程。

數據庫架構

我們今天做的腳本使用了兩個表。第一個為啟用了欣賞按鈕的每個頁面保存一個記錄。第二個存儲沿著頁面的唯一 ID 投票的人的 IP。通過這種方式,我們可以輕鬆確定此人之前是否曾為該頁面投票並顯示相應版本的按鈕(激活或禁用)。

哈希字段包含一個 MD5 頁面 URL 的總和。這樣我們添加了一個 UNIQUE 將加快選擇的索引 我們在記錄上運行,並確保表中沒有重複的記錄。 讚賞 列保存頁面的欣賞次數。

欣賞投票 表包含已投票的人的 IP(以整數的形式),以及來自 appreciate_pages 的頁面的 id 桌子。當插入發生時,時間戳會自動更新為當前時間。

您可以通過運行 tables.sql 中的代碼來創建這兩個表 在 SQL phpMyAdmin 部分 來自可下載的存檔,是本教程的一部分。

第 1 步 - XHTML

讓我們從本教程的 XHTML 部分開始。頁面的標記非常簡單。要讓欣賞按鈕發揮作用,您只需要提供一個插入按鈕的容器和一個可選元素,該元素保存按鈕的總點擊次數。你可以放心地省略後一個,只留下一個 div 來編碼。

page.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>An AJAX Click To Appreciate Badge</title>

<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="appreciateMe/appreciate.css"/>
</head>

<body>

<div id="countDiv"></div>
<div id="main"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="appreciateMe/plugin.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>

</body>
</html>

在上面的頁面中,您可以看到我包含了兩個樣式表文件。第一個是styles.css, 用於設置頁面樣式,以及 appreciate.css ,位於插件目錄下,負責鑑賞按鈕的樣式。

在結束 body 標記之前,您可以看到我還包含來自 Google 的 CDN 存儲庫的 jQuery 庫 plugin.js 文件和 script.js ,它使用插件在頁面上創建按鈕。您只需要更改 script.js 的內容 使腳本在您的頁面上運行。

第 2 步 - PHP

PHP 處理數據庫交互並位於 AJAX 請求的後端。大部分腳本邏輯位於c script.php 您可以在下面看到。但首先讓我們看一下connect.php, 它處理數據庫連接。

appreciateMe/connect.php

$db_host = 'localhost';
$db_user = 'YourUsername';
$db_pass = 'YouPassword';
$db_name = 'NameOfDB';

@$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

if (mysqli_connect_errno()) {
    die('<h1>Could not connect to the database</h1>');
}

$mysqli->set_charset("utf8");

到目前為止,我們一直使用舊的 mysql PHP 下數據庫連接的擴展,因為它更易於使用,並且我想讓代碼與 PHP 4 兼容。但是,隨著最近宣布 WordPress(我們最喜歡的博客引擎)將放棄對該版本的 PHP 的支持,我決定是時候切換到新版本了——MySQLi(MySQL改進了)。

從上面的代碼可以看出,與我們連接數據庫的舊方式的唯一主要區別是,這裡我們創建了一個 MySQLi 對象而不是使用 mysql_ 功能。此外,稍後您將看到,當我們查詢數據庫時,會返回一個 MySQL 資源對象,該對象又具有自己的一組方法。這聽起來可能令人生畏,但一旦你看到它的實際效果就會變得非常清楚。

欣賞我/script.php

/* Setting the error reporting level */
error_reporting(E_ALL ^ E_NOTICE);
include 'connect.php';

if(!$_GET['url'] || !filter_input(INPUT_GET,'url',FILTER_VALIDATE_URL)){
    exit;
}

$pageID         = 0;
$appreciated    = 0;
$jsonArray      = array();
$hash           = md5($_GET['url']);
$ip             = sprintf('%u',ip2long($_SERVER['REMOTE_ADDR']));

// $result is an object:
$result = $mysqli->query("SELECT id,appreciated FROM appreciate_pages WHERE hash='".$hash."'");

if($result)
{
    list($pageID,$appreciated) = $result->fetch_row();
    // fetch_row() is a method of result
}

// The submit parameter denotes that we need to write to the database

if($_GET['submit'])
{
    if(!$pageID)
    {
        // If the page has not been appreciated yet, insert a new
        // record to the database.

        $mysqli->query("
            INSERT INTO appreciate_pages
            SET
                hash='".$hash."',
                url='".$mysqli->real_escape_string($_GET['url'])."'"
        );

        if($mysqli->affected_rows){

            // The insert_id property contains the value of
            // the primary key. In our case this is also the pageID.

            $pageID = $mysqli->insert_id;
        }
    }

    // Write the vote to the DB, so the user can vote only once

    $mysqli->query("
        INSERT INTO appreciate_votes
        SET
            ip = ".$ip.",
            pageid = ".$pageID
    );

    if($mysqli->affected_rows){
        $mysqli->query("
            UPDATE appreciate_pages
            SET appreciated=appreciated+1 WHERE id=".$pageID
        );

        // Increment the appreciated field
    }

    $jsonArray = array('status'=>1);
}
else
{
    // Only print the stats

    $voted = 0;

    // Has the user voted?
    $res = $mysqli->query("
        SELECT 1 FROM appreciate_votes
        WHERE ip=".$ip." AND pageid=".$pageID
    );

    if($res->num_rows){
        $voted = 1;
    }

    $jsonArray = array('status'=>1,'voted'=>$voted,'appreciated'=>$appreciated);
}

// Telling the browser to interpret the response as JSON:
header('Content-type: application/json');

echo json_encode($jsonArray);

該腳本處理兩種不同類型的 AJAX 請求 - 只讀請求 (返回一個 JSON 對象,其中包含頁面的點贊次數,以及當前用戶是否點擊了按鈕),以及 write requests (將訪問者的投票保存到數據庫中,如果需要,還保存頁面 URL 和哈希)。

正如您在上面的代碼片段中看到的,腳本所做的第一件事就是計算 MD5 頁面的哈希。這被用作數據庫中的唯一鍵,因為 URL 具有無限長度,這與 MySQL 的唯一鍵不兼容。由於 MD5 哈希在大多數實際用途中是獨一無二的,因此我們可以安全地在選擇和插入中使用它,而不是長 URL 地址。

在代碼的最後一行,我們將 $jsonArray 使用內置 json_encode 將數組轉換為有效的 JSON 對象 PHP 函數,並使用 application/json 輸出 內容類型。

第 3 步 - jQuery

appreciateMe裡面 目錄下你可以找到 plugin.js 文件。您必須將其包含在您希望顯示“欣賞”按鈕的頁面中。它使用 AJAX 從 PHP 後端請求數據,並使用它收到的響應來創建按鈕的標記。

欣賞我/plugin.js

function(){

    $.appreciateButton = function(options){

        // The options object must contain a URL and a Holder property
        // These are the URL of the Appreciate php script, and the
        // div in which the badge is inserted

        if(!'url' in options || !'holder' in options){
            return false;
        }

        var element = $(options.holder);

        // Forming the url of the current page:

        var currentURL =    window.location.protocol+'//'+
                    window.location.host+window.location.pathname;

        // Issuing a GET request. A rand parameter is passed
        // to prevent the request from being cached in IE

        $.get(options.url,{url:currentURL,rand:Math.random()},function(response){

            // Creating the appreciate button:

            var button = $('<a>',{
                href:'',className:'appreciateBadge',
                html:'Appreciate Me'
            });

            if(!response.voted){
                // If the user has not voted previously,
                // make the button active / clickable.
                button.addClass('active');
            }
            else button.addClass('inactive');

            button.click(function(){
                if(button.hasClass('active')){

                    button.removeClass('active').addClass('inactive');

                    if(options.count){
                        // Incremented the total count
                        $(options.count).html(1 + parseInt(response.appreciated));
                    }

                    // Sending a GET request with a submit parameter.
                    // This will save the appreciation to the MySQL DB.

                    $.getJSON(options.url,{url:currentURL,submit:1});
                }

                return false;
            });

            element.append(button);

            if(options.count){
                $(options.count).html(response.appreciated);
            }
        },'json');

        return element;
    }

})(jQuery);

該腳本基本上在主 jQuery 對像中創建了一個新方法。這與我們通常做的插件不同,因為這種類型的插件不是在一組元素上調用的(不需要選擇元素)。你可以調用 $.appreciateButton() 同時將配置對像作為參數傳遞。這正是我們在 script.js 中所做的 向頁面添加按鈕:

script.js

$(document).ready(function(){

    // Creating an appreciate button.

    $.appreciateButton({
        url     : 'appreciateMe/script.php',    // URL to the PHP script.
        holder  : '#main',              // The button will be inserted here.
        count   : '#countDiv'           // Optional. Will show the total count.
    });

});

作為參數傳遞的配置對象必須包含一個 url 和一個持有人 屬性,而 count 是可選的。請注意,我已經指定了 script.php 的路徑 相對而言,因為ThanksMe 是頁面當前所在目錄的子目錄。

但是,如果您計劃將腳本添加到具有可變路徑結構的站點,您可能應該指定絕對路徑。添加 前導斜杠 ,或使用 http:// 提供完整的 URL .

第 4 步 - CSS

現在我們已經有了所有的標記和代碼,是時候轉向樣式了。設置欣賞徽章樣式的 CSS 規則位於 appreciate.css .如果您想避免額外的請求,您可以選擇將這些規則復製到您的主樣式表文件中,但請注意您需要更改背景圖像的路徑。

appreciateMe/appreciate.css

.appreciateBadge{
    width:129px;
    height:129px;
    display:block;
    text-indent:-9999px;
    overflow:hidden;
    background:url('sprite.png') no-repeat;
    text-decoration:none;
    border:none;
}

.appreciateBadge.active{
    background-position:left top;
}

.appreciateBadge.active:hover{
    background-position:0 -129px;
}

.appreciateBadge.inactive{
    background-position:left bottom;
    cursor:default;
}

欣賞徽章圖像有三個版本。一個默認的,一個懸停的,一個非活動的。所有這三個都駐留在同一個文件中 - sprite.png ,一個低於另一個。使用這種技術,您可以通過偏移超鏈接的背景圖像在版本之間即時切換。

styles.css

#main{
    margin:80px auto;
    width:130px;
}

#countDiv{
    color:#eee;
    font-size:35px;
    margin-right:120px;
    position:absolute;
    right:50%;
    top:265px;
}

您可以找到其餘樣式,這些樣式改進了 page.html 的外觀 , 在 styles.css 中 .只有兩組樣式直接影響欣賞按鈕。 #main div,其中包含按鈕並在頁面上居中,以及 #countDiv 其中插入了總升值次數。

有了這個,我們的點擊欣賞徽章就完成了!

結論

在您的服務器上運行此腳本之前,您首先必須替換 connect.php 中的 MySQL 憑據 用你自己的。此外,您需要運行 tables.sql 的內容 在 phpMyAdmin 的 SQL 選項卡中, 所以創建了兩個表。最後,根據您的 URL 路徑,您可能需要更改 appreciateMe/script.php 的 URL 屬性 在 script.js JavaScript 文件中。


Tutorial JavaScript 教程
  1. 如何向 AWS 上的無服務器 HTTP API 添加基於角色的訪問控制

  2. 為 Diigo 創建 Chrome 擴展,第 3 部分

  3. JavaScript 遞歸

  4. JavaScript 原型是如何工作的?

  5. 更快、更好、更便宜——製作軟件的藝術

  6. 如何取消加載圖像

  7. 如何從 JavaScript 字符串中刪除無效的 UTF-8 字符?

  1. Minecraft + Node.js + Socket.io =很棒

  2. 宣布 NativeBase

  3. 純 JavaScript 中的 Glassmorphism Tab-bar

  4. 將測試添加到現有的 Vue 項目

  5. Cypress JS,是否有忽略一些網絡掛起調用

  6. 如何在您的 Web 應用程序中使用 jQuery 按鈕組 UI 組件

  7. Supabase:七個月的建設。

  1. 在 TypeScript 中解構參數時找不到錯誤

  2. 認識軟件開發人員

  3. 為什麼我收到一條錯誤消息,說 expressJwt 不是函數?

  4. 使用 Node.js 將 MongoDB 連接到您的應用程序