将 Pusher 集成到一个简单的 php 网络应用程序

Integrating Pusher to a simple php web app

你好 Whosebug 社区,我正在学习如何将 Pusher API http://pusher.com 实现到这个简单的网络聊天应用程序中。我按照视频教程进行操作并正确完成了每一步,但是当我尝试发送消息时,它会在我的网络浏览器上正确显示,但不会在其他网络浏览器上显示或刷新。我将添加我的 2 php 个文件,它们很短。

<!doctype html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title>Pusher Messenger</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
        <script src="https://js.pusher.com/3.1/pusher.min.js"></script>
        <script>

        // Enable pusher logging - don't include this in production
        //Pusher.logToConsole = true;

        var pusher = new Pusher('your pusher key here', {
          encrypted: true
        });

        var channel = pusher.subscribe('channel_pusher');
        channel.bind('new_message', function(response){
          $('#sent_messages').append('<li>' + response.message + '</li>');
        });

        $(function(){
            $('form').submit(function(){
                $.post('ajax.php', { msj : $('#input_mensaje').val() }, function(response){
                    //funcion de callback
                    $('#sent_messages').append('<li>' + response.message + '</li>');
                }, 'json');

                return false;
            });
        });
        </script>
    </head>
    <body>
        <form action="" methor="post">
            <input type="text" id="input_mensaje" />
            <input type="submit" class="submit" value="Send" />
        </form>

        <ul id="sent_messages">
            <!-- Sent messages will be shown here -->
        </ul>
    </body>
    </html>

这是我的 ajax.php 文件:

<?php
    require('lib/Pusher.php');

    $options = array(
        'encrypted' => true
    );

    $message = $_POST['msj'];

    $pusher = new Pusher(
        'code provided by pusher',
        'code provided by pusher',
        'code provided by pusher',
        $options
      );

    $pusher->trigger(
        'channel_pusher',
        'new_message',
        array('message' => $message)
    );

    echo json_encode(array('message' => $message));
?>

我刚刚用我自己的应用程序密钥测试了您的代码,它似乎工作正常。 但是,我确实注意到,虽然您在引用的 ajax.php 中包含了您的应用程序密钥和秘密(通常应该避免),但您的 HTML 仅包含

var pusher = new Pusher('your pusher key here',

请确保在两个文件中都提供应用程序密钥,以便两者都可以与 Pusher 实际通信。

另一件需要注意的事情是,您的 ajax.php 当前将从页面提交的消息传递给 Pusher 并返回给页面本身。 这样做的结果是,提交消息的页面实际上会追加两次,一次来自 ajax.php 返回的响应,一次来自 Pusher 收到的 new_message 事件。 这可能是也可能不是您的想法。