Laravel 在加载时使用 javascript 获取会话

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30163940/
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 11:31:43  来源:igfitidea点击:

Laravel get Session with javascript while loading

javascriptphpsessionlaravel

提问by Irfandi D. Vendy

Here is my scenario:

这是我的场景:

-I'm processing an excel file that'll took about ~10 minute
-While processing, I want to send a feedback to user that we are currently processing

- 我正在处理一个大约需要 10 分钟的 excel 文件 - 在
处理过程中,我想向用户发送我们当前正在处理的反馈

My idea was using Session that will put value while processing, and get that Session using javascript in current view
Here's my script:

我的想法是使用 Session 将在处理时放置值,并在当前视图中使用 javascript 获取该 Session
这是我的脚本:

<script type="text/javascript">
    $(document).ready(function() {
        var element = document.getElementById("progress");
        setInterval(
            function(){
                element.innerHTML = "{{Session::get('progress')}}";
            },500
        );
    });
</script>


And somewhere in my controller, let's just say like this:


在我的控制器的某个地方,让我们这样说:

    $i = 0;
    while(!$done){
        processingComplicated();
        Session::put('progress', $i);
        Session::save();
    }


And my basic view :


我的基本观点:

<div id="progress">0</div>

Basically, I want the current page to get the Session data and update the view(id="progress"), but the it won't change.
Can it be done? Thanks.

基本上,我希望当前页面获取会话数据并更新视图(id="progress"),但它不会改变。
可以做到吗?谢谢。

采纳答案by SkarXa

Use AJAXto update the view

使用AJAX更新视图

$(document).ready(function() {
    var element = document.getElementById("progress");
    setInterval(
        function(){
            $.get( "processing-status", function( data ) {
                 element.innerHTML = data;
            });
        },500
    );
});

And in your routes, controller or wherever you want

在你的路线、控制器或任何你想要的地方

Route::get('/processing-status', function()
{
    return Session::get('progress');
});