JavaScript >> Javascript 文檔 >  >> jQuery

教程:使用 PHP 和 jQuery 製作 Shoutbox

在本教程中,我們將使用 PHP 和 jQuery 構建一個喊話框,它允許您網站的訪問者互相留下簡短的評論。 Shouts 將作為文件存儲在服務器上,不需要像 MySQL 這樣的數據庫。我們將使用兩個 PHP 庫來讓事情變得更簡單——Flywheel 用於將喊聲存儲為 json 文件,RelativeTime 用於創建人類可讀的相對時間戳。我們將使用 Composer 來安裝這些庫。

在客戶端,我們使用純 jQuery 代碼和 Emoji One 庫,這是一個免費項目和庫,用於將漂亮的表情符號添加到 Web 應用程序中。開始吧!

運行喊話箱

您可以從上面的下載按鈕獲取源代碼。它有很多評論,很容易理解。要運行它,只需將它上傳到您的網絡託管空間,或者如果您運行 XAMPP 或 MAMP 之類的東西,則將其添加到 apache htdocs 文件夾中。然後,在您的瀏覽器(或您的網站,如果您將其上傳到您的託管空間)中打開 http://localhost。以下是一些需要注意的事項:

  • zip 文件已經包含依賴項,因此您無需安裝 Composer。這使得開始使用代碼變得很容易 - 只需上傳並使用它!
  • 確保 data/shouts 目錄存在且可寫。否則,您將在日誌文件中看到錯誤,並且不會存儲任何呼喊。如果您不斷看到錯誤,您可能需要將其更改為 777。

HTML

讓我們從index.html開始 .它是一個常規的 HTML5 文檔,其中包括我們的 JavaScript 庫、腳本和样式表。以下是與喊話箱相關的部分:

index.html

<div class="shoutbox">

    <h1>Shout box <img src='./assets/img/refresh.png'/></h1>

    <ul class="shoutbox-content"></ul>

    <div class="shoutbox-form">
        <h2>Write a message <span>×</span></h2>

        <form action="./publish.php" method="post">
            <label for="shoutbox-name">nickname </label> <input type="text" id="shoutbox-name" name="name"/>
            <label class="shoutbox-comment-label" for="shoutbox-comment">message </label> <textarea id="shoutbox-comment" name="comment" maxlength='240'></textarea>
            <input type="submit" value="Shout!"/>
        </form>
    </div>

</div>

使用 JavaScript,我們會將發布的喊聲插入到

    元素中。表單默認隱藏,只有在點擊“寫消息”標題時才會顯示。

    JavaScript 代碼

    這是我們的 script.js ,這使得上面的 HTML 工作:

    assets/js/script.js

    $(function(){
    
        // Storing some elements in variables for a cleaner code base
    
        var refreshButton = $('h1 img'),
            shoutboxForm = $('.shoutbox-form'),
            form = shoutboxForm.find('form'),
            closeForm = shoutboxForm.find('h2 span'),
            nameElement = form.find('#shoutbox-name'),
            commentElement = form.find('#shoutbox-comment'),
            ul = $('ul.shoutbox-content');
    
        // Replace :) with emoji icons:
        emojione.ascii = true;
    
        // Load the comments.
        load();
    
        // On form submit, if everything is filled in, publish the shout to the database
    
        var canPostComment = true;
    
        form.submit(function(e){
            e.preventDefault();
    
            if(!canPostComment) return;
    
            var name = nameElement.val().trim();
            var comment = commentElement.val().trim();
    
            if(name.length && comment.length && comment.length < 240) {
    
                publish(name, comment);
    
                // Prevent new shouts from being published
    
                canPostComment = false;
    
                // Allow a new comment to be posted after 5 seconds
    
                setTimeout(function(){
                    canPostComment = true;
                }, 5000);
    
            }
    
        });
    
        // Toggle the visibility of the form.
    
        shoutboxForm.on('click', 'h2', function(e){
    
            if(form.is(':visible')) {
                formClose();
            }
            else {
                formOpen();
            }
    
        });
    
        // Clicking on the REPLY button writes the name of the person you want to reply to into the textbox.
    
        ul.on('click', '.shoutbox-comment-reply', function(e){
    
            var replyName = $(this).data('name');
    
            formOpen();
            commentElement.val('@'+replyName+' ').focus();
    
        });
    
        // Clicking the refresh button will force the load function
    
        var canReload = true;
    
        refreshButton.click(function(){
    
            if(!canReload) return false;
    
            load();
            canReload = false;
    
            // Allow additional reloads after 2 seconds
            setTimeout(function(){
                canReload = true;
            }, 2000);
        });
    
        // Automatically refresh the shouts every 20 seconds
        setInterval(load,20000);
    
        function formOpen(){
    
            if(form.is(':visible')) return;
    
            form.slideDown();
            closeForm.fadeIn();
        }
    
        function formClose(){
    
            if(!form.is(':visible')) return;
    
            form.slideUp();
            closeForm.fadeOut();
        }
    
        // Store the shout in the database
    
        function publish(name,comment){
    
            $.post('publish.php', {name: name, comment: comment}, function(){
                nameElement.val("");
                commentElement.val("");
                load();
            });
    
        }
    
        // Fetch the latest shouts
    
        function load(){
            $.getJSON('./load.php', function(data) {
                appendComments(data);
            });
        }
    
        // Render an array of shouts as HTML
    
        function appendComments(data) {
    
            ul.empty();
    
            data.forEach(function(d){
                ul.append('<li>'+
                    '<span class="shoutbox-username">' + d.name + '</span>'+
                    '<p class="shoutbox-comment">' + emojione.toImage(d.text) + '</p>'+
                    '<div class="shoutbox-comment-details"><span class="shoutbox-comment-reply" data-name="' + d.name + '">REPLY</span>'+
                    '<span class="shoutbox-comment-ago">' + d.timeAgo + '</span></div>'+
                '</li>');
            });
    
        }
    
    });

    Emoji One 庫具有 JavaScript 和 PHP 版本。在 appendComments 方法中,我們使用 emojione.toImage() 函數將所有輸入的笑臉轉換為表情符號。查看所有受支持的功能,並查看這個方便的表情符號代碼網站。現在前端已經準備好了,讓我們繼續進行後端吧。

    PHP 代碼

    我們有兩個文件 - publish.php 和 load.php。第一個接受 POST 請求,將喊叫存儲在數據存儲中,第二個返回 20 個最新的喊叫。這些文件不是由訪問者直接打開的——它們只處理 AJAX 請求。

    publish.php

    <?php
    
    // Include our composer libraries
    require 'vendor/autoload.php';
    
    // Configure the data store
    
    $dir = __DIR__.'/data';
    
    $config = new \JamesMoss\Flywheel\Config($dir, array(
        'formatter' => new \JamesMoss\Flywheel\Formatter\JSON,
    ));
    
    $repo = new \JamesMoss\Flywheel\Repository('shouts', $config);
    
    // Store the posted shout data to the data store
    
    if(isset($_POST["name"]) && isset($_POST["comment"])) {
    
        $name = htmlspecialchars($_POST["name"]);
        $name = str_replace(array("\n", "\r"), '', $name);
    
        $comment = htmlspecialchars($_POST["comment"]);
        $comment = str_replace(array("\n", "\r"), '', $comment);
    
        // Storing a new shout
    
        $shout = new \JamesMoss\Flywheel\Document(array(
            'text' => $comment,
            'name' => $name,
            'createdAt' => time()
        ));
    
        $repo->store($shout);
    
    }

    這裡我們直接使用我們一開始提到的Flywheel庫。配置完成後,您可以存儲任何類型的數據,這些數據將作為 JSON 文件寫入 data/shouts 文件夾中。閱讀這些呼喊是在 load.php 中完成的:

    加載.php

    <?php
    
    require 'vendor/autoload.php';
    
    // If you want to delete old comments, make this true. We use it to clean up the demo.
    $deleteOldComments = false;
    
    // Setting up the data store
    
    $dir = __DIR__.'/data';
    
    $config = new \JamesMoss\Flywheel\Config($dir, array(
        'formatter' => new \JamesMoss\Flywheel\Formatter\JSON,
    ));
    
    $repo = new \JamesMoss\Flywheel\Repository('shouts', $config);
    
    // Delete comments which are more than 1 hour old if the variable is set to be true.
    
    if($deleteOldComments) {
    
        $oldShouts = $repo->query()
                    ->where('createdAt', '<', strtotime('-1 hour'))
                    ->execute();
    
        foreach($oldShouts as $old) {
            $repo->delete($old->id);
        }
    
    }
    
    // Send the 20 latest shouts as json
    
    $shouts = $repo->query()
            ->orderBy('createdAt ASC')
            ->limit(20,0)
            ->execute();
    
    $results = array();
    
    $config = array(
        'language' => '\RelativeTime\Languages\English',
        'separator' => ', ',
        'suffix' => true,
        'truncate' => 1,
    );
    
    $relativeTime = new \RelativeTime\RelativeTime($config);
    
    foreach($shouts as $shout) {
        $shout->timeAgo = $relativeTime->timeAgo($shout->createdAt);
        $results[] = $shout;
    }
    
    header('Content-type: application/json');
    echo json_encode($results);

    我們已經包含刪除超過一小時的喊叫的代碼。我們使用此功能來保持演示乾淨。如果您願意,可以啟用它。在選擇了呼喊之後,我們也在使用 RelativeTime 庫計算人類可讀的相對時間戳。

    有了這個,我們的喊話箱就準備好了!您可以將其嵌入到您的網站中,對其進行自定義並以任何您喜歡的方式更改代碼。我們希望你喜歡它!


Tutorial JavaScript 教程
  1. 團隊成員名稱雜耍應用

  2. 只需 10 分鐘即可構建 JavaScript 倒數計時器

  3. 無聊的?試試我的第一個應用程序!

  4. 反應/Redux 項目

  5. Ember 2.0 有什麼新功能?

  6. Metrics v3.0,拉皮條你的 GitHub 個人資料的終極工具!

  7. Angular Dart 路由器 - 配置 LocationStrategy

  1. 對象未存儲到本地存儲中。 – 反應 JS

  2. 如果您是移動開發人員,您應該了解 Reactjs

  3. 將 GraphQL 添加到 Nx 工作區中的 NestJS API

  4. 如何在反應中向您的 chrome 擴展添加上下文菜單

  5. 如何使 2 個 Quasar 切換按鈕組互斥?

  6. ES6 承諾 |承諾.all |承諾.race | Promise.all 已解決

  7. JavaScript - 全局變量

  1. 學習 Tailwindcss 的動手體驗課程

  2. 使用 React Http Request Handler (RH2) 一個 React 庫輕鬆處理 React 和 React Native 的 http 請求

  3. 在同一個端口上開發 Express 和 React

  4. 如何在 React Native 中創建帶有驗證的自定義表單並滾動到無效邏輯(第二部分: 滾動到無效)