2016-06-25 74 views
0

你好stackoverflow社区,我正在学习如何实现Pusher API http://pusher.com到这个简单的网络聊天应用程序。我正在按照视频教程正确执行每一步,但当我尝试发送消息时,它会在我的网络浏览器上正确显示,但不会在其他网络浏览器上显示或刷新。我将添加我的2个PHP文件,它们很短。集成Pusher到一个简单的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)); 
?> 
+0

欢迎来到StackOverflow。听起来像你应该指定在哪个浏览器中正确地为你工作,并且在哪个浏览器中没有。还是其他任何浏览器,包括另一台PC上的相同浏览器和PC上的另一台浏览器? – YakovL

+0

是的,你是对的,它不会刷新任何网页浏览器,主要问题是它没有显示实时消息。例如:我写了“Hello”,它会将其显示在我的网络浏览器上,但如果旁边有另一个网络浏览器,则不会显示任何消息。 –

+0

我可以得到一些帮助吗? –

回答

0

我刚才用我自己的应用程序键测试你的代码,它似乎很好地工作。 我没有通知,但是,当你包括在你引用(通常应避免)的ajax.php您的应用程序密钥和密码,您的HTML只包含

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

请务必提供应用程序键在两个文件中都可以实现与Pusher的实际通信。

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

+0

haha​​haha,对不起,这是事情,我从推进器对象中删除了我的应用程序密钥,我在这个论坛公开的关键,但我忘了在ajax文件上删除它,反正它是一个简单的网络应用程序,所以我不在乎,我可以要求一个新的。所以对于你提到的第二件事,它会重复两次,因为该函数是两次,以避免你需要添加一个名为socket_id的参数:pusher.connection.socket_id;并成为ajax触发器功能,但我试过了,它不起作用。另外,我正在运行WAMP,它可能与我的网络浏览器有关,但它不起作用? –

相关问题