发送消息后,聊天不会实时出现。它需要刷新页面以获取消息。我从A发送一条消息,我必须在B端刷新以获取该消息。知道为什么吗?
脚本
<script src="https://js.pusher.com/6.0/pusher.min.js"></script>
<script>
var receiver_id = '';
var my_id = "{{ Auth::id() }}";
$(document).ready(function () {
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('97ac3a8652d7c9cc98dc', {
cluster: 'ap2',
forceTLS: true
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});
});
</script>
控制器
public function sendMessage(Request $request)
{
$from = Auth::id();
$to = $request->receiver_id;
$message = $request->message;
$data = new Message();
$data->from = $from;
$data->to = $to;
$data->message = $message;
$data->is_read = 0; // message will be unread when sending message
$data->save();
// pusher
$options = array(
'cluster' => 'ap2'
);
$pusher = new Pusher(
env('PUSHER_APP_KEY'),
env('PUSHER_APP_SECRET'),
env('PUSHER_APP_ID'),
$options
);
$data = ['from' => $from, 'to' => $to]; // sending from and to user id when pressed enter
$pusher->trigger('my-channel', 'my-event', $data);
}