我正在尝试使用 socket.io。并想从我的 javascript(客户端)发送一个变量到 laravel 事件,然后将其传递回客户端。我在我的代码中评论了我想要的。
下面是我的代码:
事件:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class MarketUpdate implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets;
public $data;
public function __construct()
{
$this->data = [
'abcd' => $id , /// I need to get this ID from client side.
];
}
public function broadcastOn()
{
return array('channel_test');
}
}
客户端JS:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script>
var id = '9';
var socket = io('http://localhost:8890');
socket.on("channel_test:App\\Events\\EventNew", function (message) {
// I Want to send id here somewhere and display
$('#abcd').html(message.data.abcd);
});
</script>