dsgnze6572 2016-11-25 15:45
浏览 64

AjaX调用期间的进度仅显示初始值和最终值

I need to execute an AjaX call to a PHP script with a long execution time. My goal is to display a progress status of this execution.

The idea is to create an AjaX call to periodically ask the server about the status of the execution. The progress status is stored into $_SESSION['progress'], initially set to 0 and changed from script during execution.

Here's my code on client and server side.

Client-side

// invoke the script (ie. with button)
$('#start').click(function()
{
    $.ajax
    ({
        url: "long-script.php"
    });
});

// check progress periodically
setInterval(progress, 100);
function progress() 
{ 
    $.ajax
    ({
        dataType: "json",
        url: "progress.php",

        success: function(data) 
        {
            console.log(data);
        }
    });
}

long-script.php

// just an example to emulate execution
sleep(1);
$_SESSION['progress']=30;
sleep(1);
$_SESSION['progress']=70;
sleep(1);
$_SESSION['progress']=100;

progress.php

header('Content-Type: application/json');
echo json_encode($_SESSION['progress']);

The problem is that console.log() in progress function outputs 0 before the script execution, stops outputing data during the execution, and finally outputs 100 when the script is terminated. What am I missing?

  • 写回答

1条回答 默认 最新

  • dongzen7263 2016-11-25 16:06
    关注

    The problem is that the session is not written, until the script ends, or the session closes.

    You need to remember that sessions, by default in php are stored as files on the system and is locked in run-time.

    What you can do is change the long-script.php file a bit.

    session_start();
    
    sleep(1);
    $_SESSION['progress']=30;
    session_write_close();
    
    sleep(1);
    session_start();
    $_SESSION['progress']=70;
    session_write_close();
    
    sleep(1);
    session_start();
    $_SESSION['progress']=100;
    session_write_close();
    

    The idea is to write to the session after every progress changes.

    Then you will need to start the session again.

    This may be a wrong way to do this, but you can always look up the session functions in php. Take a look at this session_write_cloe

    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私