我正在尝试在用户登录时运行 JavaScript 库 Noty。我已经注册了该事件并按照文档 here 进行操作。不过,我尝试使用 echo 发送 javascript,但从我所看到的来看,代码并未执行。工作流程是,在Home
页面登录时,会弹出一条通知,表示欢迎。
这是我的EventServiceProvider
:
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
'Illuminate\Auth\Events\Login' => ['App\Listeners\UserEventListener@onUserLogin']
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
}
}
UserEventListener
:
class UserEventListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param Login $event
* @return void
*/
public function handle(Login $event)
{
}
public function onUserLogin($event) {
echo("<script>
$(document).ready(function() {
new Noty({
text: 'Welcome {{Auth::user()->name}}! 😁',
type:'info',
layout: 'centerRight',
timeout:2000
})
.on('onShow', function() {
var audio = new Audio('/sounds/appointed.mp3');
audio.play();
}).show();
});
</script>");
echo("adad");
}
}
最佳答案
这似乎是一种使用 Laravel 显示消息的非常奇怪的方法。
您可以简单地在登录 Controller 中使用此行
return redirect('your/path')->with('success', '这里是您的消息');
在 Blade 模板的某个位置执行简单检查:
@if (\Session::has('success'))
<script>
$(document).ready(function() {
new Noty({
text: 'Welcome {{ Auth::user()->name }}',
type:'info',
layout: 'centerRight',
timeout:2000
})
.on('onShow', function() {
var audio = new Audio('/sounds/appointed.mp3');
audio.play();
}).show();
});
</script>
@endif
您可以将通知代码放在通用(例如布局)模板中,这样如果用户 session 中有消息,它将在任何地方触发通知
关于javascript - 在 Laravel 5.7 事件监听器中运行 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54184388/