Laravel 5.4中没有弹出脚本警报

时间:2017-03-10 06:52:44

标签: javascript laravel laravel-5 popup alert

我为文件上传开发了laravel 5.4。如果我上传它需要弹出te sucess alert但它不会出现在这里。

这是我在Laravel 5.4中的布局

  <!DOCTYPE html>
<html lang="{{ config('app.locale') }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

    <!-- Scripts -->
    <script>
        window.Laravel = {!! json_encode([
            'csrfToken' => csrf_token(),
        ]) !!};
    </script>
</head>
<body>
        @yield('content')
    </div>
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>

</body>
</html>

这是UploadController的必要部分

else if($validator -> passes()){
        if(Input::file('filenam')->isValid()){
            $extention=Input::file('filenam')->getClientOriginalExtension();
            $filename=rand(11111,99999).'.'.$extention;

            $destinationPath='up_file';
            $file->move($destinationPath, $filename);

            $notification = array(
                'message' => 'File Uploaded Successfully',
                'alert-type' => 'success'
                );

            return Redirect::to('upload')->with($notification);
        }
        else{
            $notification = array(
                'message' => 'File is not Valid!',
                'alert-type' => 'error'
                );

            return Redirect::to('upload')->with($notification);

以及视图的脚本部分

    <script>
    @if(Session::has('message'))
    var type ="{{ Session::get('alert-type', 'info')}}";
    switch(type){
        case 'success':
        toastr.success("{{ Session::get('message')}}");
        break;

        case 'error': 
        toastr.error("{{ Session::get('message')}}");
        break;
    }
    @endif
</script>

任何人都可以在这里提出问题。 谢谢。

1 个答案:

答案 0 :(得分:0)

那是因为您正在检查是否Session::has('message')但是您没有将变量保存到Session。但是,您只需传递一个$notification变量,该变量也无法访问您的视图,因为您刚刚执行了with($notification)With()要么需要2个参数,例如with('name', $value)withName($value),您的视图才能访问变量。

要解决您的问题,请在您的控制器中执行以下操作

$notification = array(
    'message' => 'File Uploaded Successfully',
    'alert-type' => 'success'
);

// saves $notification to the Session object
session()->put($notification); // or  \Session::put($notification); whichever you prefer

return Redirect::to('upload');

在您看来,

@if(Session::has('message'))
    <script>
        var type ="{{ Session::get('alert-type') }}";
        var msg = "{{ Session::get('message') }}";
        switch(type){
            case 'success':
                toastr.success(msg);
                break;

            case 'error': 
                toastr.error(msg);
                break;
        }
    </script>
@endif
相关问题