laravel 拉拉维尔 | 如何在 JavaScript 中访问会话数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43683692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:52:33  来源:igfitidea点击:

laravel | How to access session array in JavaScript?

javascriptarrayslaravellaravel-5.4laravel-blade

提问by Sapnesh Naik

I am passing an array to a view from my controller.

我正在将一个数组从我的控制器传递给一个视图。

Here is the controller function:

这是控制器功能:

$notification = array(
            'message' => 'Welcome Admin!', 
            'alert_type' => 'success',
        );
return redirect('/home')->with('notification', $notification);

In my view:

在我看来:

<script>
  @if(Session::has('notification'))//this line works as expected

    var type = "{{ Session::get('alert_type', 'info') }}";
   //but the type var gets assigned with default value(info)
    switch(type){
        case 'info':
            toastr.info("{{ Session::get('message') }}");
            break;

        case 'warning':
            toastr.warning("{{ Session::get('message') }}");
            break;

        case 'success':
            toastr.success("{{ Session::get('message') }}");
            break;

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

as you can see there's clearly something wrong with the way I am trying to access the array value in var type = "{{ Session::get('alert_type', 'info') }}";

正如你所看到的,我试图访问数组值的方式显然有问题 var type = "{{ Session::get('alert_type', 'info') }}";

EDIT- 1: I tried doing

编辑- 1:我试过做

var type = "{{ Session::get('notification')->alert_type, 'info' }}";
switch(type){
    case 'info':
        toastr.info("{{ Session::get('notification')->message }}");
        break;

    case 'warning':
        toastr.warning("{{ Session::get('notification')->message }}");
        break;

    case 'success':
        toastr.success("{{ Session::get('notification')->message }}");
        break;

    case 'error':
        toastr.error("{{ Session::get('notification')->alert_type }}");
        break;
}

but now I get an error saying

但现在我收到一条错误消息

Trying to get property of non-object (View: C:\xampp\htdocs\financetest1\resources\views\layouts\master.blade.php) (View: C:\xampp\htdocs\financetest1\resources\views\layouts\master.blade.php)

试图获取非对象的属性(视图:C:\xampp\htdocs\financetest1\resources\views\layouts\master.blade.php)(视图:C:\xampp\htdocs\financetest1\resources\views\layouts\ master.blade.php)

can anyone please help me with this?

任何人都可以帮我解决这个问题吗?

回答by Marwelln

You should keep your PHP and Javascript code seperated. Use dataattributes in your HTML and fetch the values in your Javascript code instead.

您应该将 PHP 和 Javascript 代码分开。data在您的 HTML 中使用属性并在您的 Javascript 代码中获取值。

For example this HTML code (I use json_encodeto support line breaks):

例如这个 HTML 代码(我json_encode用来支持换行符):

<body {{ Session::has('notification') ? 'data-notification' : '' }} data-notification-type='{{ Session::get('alert_type', 'info') }}' data-notification-message='{{ json_encode(Session::get('message')) }}'>
    // ...
</body>

Then in your JS file:

然后在你的 JS 文件中:

(function(){
    // Don't go any further down the script if [data-notification] is not set.
    if ( ! document.body.dataset.notification)
        return false;

    var type = document.body.dataset.notificationType;
    switch(type){
        case 'info':
            toastr.info(JSON.parse(document.body.dataset.notificationMessage));
            break;

        case 'warning':
            toastr.warning(JSON.parse(document.body.dataset.notificationMessage));
            break;

        case 'success':
            toastr.success(JSON.parse(document.body.dataset.notificationMessage));
            break;

        case 'error':
            toastr.error(JSON.parse(document.body.dataset.notificationMessage));
            break;
    }
})();

You can shorten your JS by doing this:

您可以通过执行以下操作来缩短您的 JS:

(function(){
    // Don't go any further down the script if [data-notification] is not set.
    if ( ! document.body.dataset.notification)
        return false;

    var type = document.body.dataset.notificationType;
    var types = ['info', 'warning', 'success', 'error'];

    // Check if `type` is in our `types` array, otherwise default to info.
    toastr[types.indexOf(type) !== -1 ? type : 'info'](JSON.parse(document.body.dataset.notificationMessage));

    // toastr['info']('message') is the same as toastr.info('message')
})();


Read more on: HTMLElement.dataset, Conditional (ternary) Operator

阅读更多内容:HTMLElement.dataset条件(三元)运算符

回答by milo526

Instead of {{ Session::get('message') }}

代替 {{ Session::get('message') }}

try {{ Session::get('notification')->message }}and { Session::get('notification')->alert_type }}respectively.

分别尝试{{ Session::get('notification')->message }}{ Session::get('notification')->alert_type }}

Your session message returns the array, you will need to use the array keys to get the message not the keys directly.

您的会话消息返回数组,您需要使用数组键来获取消息而不是直接获取键。

回答by Sapnesh Naik

Okay after taking hints from @milo526 answer I did some more research and found the solution. @milo526's solution tries to access the array as an object so Laravel quacked. I did this and it works now!

好的,在从@milo526 答案中得到提示后,我做了更多研究并找到了解决方案。@milo526 的解决方案试图将数组作为对象访问,因此 Laravel 嘎嘎叫。我这样做了,现在可以使用了!

var type = "{{ Session::get('notification')['alert_type'], 'info' }}";
switch(type){
    case 'info':
        toastr.info("{{ Session::get('notification')['message'] }}");
        break;

    case 'warning':
        toastr.warning("{{ Session::get('notification')['message'] }}");
        break;

    case 'success':
        toastr.success("{{ Session::get('notification')['message'] }}");
        break;

    case 'error':
        toastr.error("{{ Session::get('notification')['message'] }}");
        break;
}