使用AJAX检查PHP脚本的进度 [英] Checking progress of a PHP script with AJAX

查看:107
本文介绍了使用AJAX检查PHP脚本的进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  session_start(); 

if(isset($ _ GET ['progress'])){
$ status_done ='0';

if($ _ SESSION ['progress_percentage'] ==100){
$ status_done ='1';


echo json_encode(array(
'progress_percentage'=> $ _SESSION ['progress_percentage'],
'progress_status'=> $ _SESSION ['' progress_status'],
'progress_done'=> $ status_done

);
}
elseif(isset($ _ GET ['dummytask'])){
for($ i = 1; $ i <= 100; $ i ++){
$ _SESSION ['progress_percentage'] = $ i;
$ _SESSION ['progress_status'] ='检查锁和玩具娃娃!';
sleep(1);






  $(document).ready(function(){
var timeout ='';

function checkProgress(){
console.log('Checking进度事件开始');

$ .ajax({
url:'http://willetu54.fiftyfour.axc.nl/dgi/ajax.php?progress&time='+ new Date().getTime(),
cache:false,
dataType:'json'
})。done(function(data){
$('#progressbar- (data.progress_status +'('+ data.progress_percentage +')');

console.log('Progress checked');
console.log(data );

if(data.progress_done ==1){
clearTimeout(timeout);
}
})。fail(function(jqXHR,状态,错误){
console.log('Check Progress:Error:'+ error + status +'');
});


$ b函数checkProgressTimeout(){
checkProgress();
console.log('Timeout tick for progress');

timeout = setTimeout(checkProgressTimeout,500);


$('#menu-open')。click(function(event){
checkProgressTimeout();

console.log '开始虚拟任务');

event.preventDefault();

$ .get('http://willetu54.fiftyfour.axc.nl/dgi/ajax。 php?dummytask',function(data){
alert('Load was performed。');
});
});
});

你好,再次Stackoverflow!

我目前正在开发的系统有脚本,运行速度很慢,有时可能会持续20秒。 (创建大量文件夹,移动大量文件等)。这就是为什么我设计了这个脚本。我创建了一个只需要持续〜100秒的小型dummytask。当我使用AJAX触发该脚本时,它完成了一定数量的任务。每当任务完成时,我用脚本的进度更新我的 $ _ SESSION 变量,并用另一个jQuery脚本将它加载到我的页面上。

但它有点奇怪。我认为它启动了 checkProgressTimeout 和虚拟任务(使用 checkProgressTimeout 函数每500毫秒检查一次进度) ,但是当我查看控制台时,我发现它只触发了事件,但是没有得到任何结果,直到虚拟任务完成,然后它以相同的timeval(500毫秒)慢速返回进度检查。

Google Chrome中会出现此问题。该脚本在IE中完全不起作用。



我设置了一个jsFiddle: http://jsfiddle.net/nZAs4/2/ 。但由于jsFiddle不支持PHP脚本,我已经有权将其自己上传到我自己的虚拟主机之一。 (我也允许访问控制 - 允许 - 来源)。

那么我怎么才能使这个工作?



默认情况下,你的会话变量不是其他脚本可以访问,直到当前脚本终止。您必须在完成处理会话数据后调用session_write_close()才能保留数据。



这可以完成如下所示:
$ b


  1. 开始会话

  2. 为此运行脚本创建数据库条目

  3. 更新会话以记录此记录的索引
  4. 关闭会话以编写 session_write_close();

    • 这允许您的监控脚本开始工作


  5. 运行处理部分该脚本(需要很长时间)
    在监视脚本上更新数据库条目及其进度


  1. 开始会话(这会挂起,直到另一个脚本中的同一个会话完成/写入关闭为止)
  2. 检查会话索引作业

  3. 从数据库获取数据

  4. 显示进度

  5. 关闭会话


    session_start();

    if(isset($_GET['progress'])){
        $status_done = '0';

        if($_SESSION['progress_percentage'] == "100"){
            $status_done = '1';
        }

        echo json_encode(array(
            'progress_percentage' => $_SESSION['progress_percentage'],
            'progress_status' => $_SESSION['progress_status'],
            'progress_done' => $status_done
            )
        );
    }
    elseif(isset($_GET['dummytask'])){
        for ($i = 1; $i <= 100; $i++) {
            $_SESSION['progress_percentage'] = $i;
            $_SESSION['progress_status'] = 'Checking the locks and stuffing the dolls!';
            sleep(1);
        }
    }

        $(document).ready(function(){   
            var timeout = '';

            function checkProgress(){
                console.log('Checking progress event started');

                $.ajax({
                    url: 'http://willetu54.fiftyfour.axc.nl/dgi/ajax.php?progress&time='+ new Date().getTime(),
                    cache: false,
                    dataType: 'json'
                }).done(function(data) {
                    $('#progressbar-progress').html(data.progress_status +'('+ data.progress_percentage +')');

                    console.log('Progress checked');
                    console.log(data);

                    if(data.progress_done == "1"){
                        clearTimeout(timeout);
                    }
                }).fail(function(jqXHR, status, error){
                    console.log('Check Progress: Error: '+ error + status +'');
                });

            }

            function checkProgressTimeout(){
                checkProgress();
                console.log('Timeout tick for progress');

                timeout = setTimeout(checkProgressTimeout, 500);
            }

            $('#menu-open').click(function(event){
                checkProgressTimeout();

                console.log('starting dummy task');

                event.preventDefault();

                $.get('http://willetu54.fiftyfour.axc.nl/dgi/ajax.php?dummytask', function(data) {
                    alert('Load was performed.');
                });
            });
        });

Hello again Stackoverflow!

The system I'm currently developing has scripts that run quite slow and can last up to 20 seconds sometimes. (Creating large amounts of folders, moving large amounts of files, etc). So thats why I've designed this script. I've created a small dummytask wich just lasts ~100 seconds. When I fire that script using AJAX it completes a certain amount of tasks. Every time a task completes I update my $_SESSION variable with the scripts' progress and load that onto my page with another jQuery script.

But it works out kinda strange. I think it does launch the checkProgressTimeout and the dummy task (With the checkProgressTimeout function it checks the progress every 500 ms), But when I look in console I see it only fires the event but does not get any results untill the dummy task is completed and then it slowely returns the progress checking with the same timeval (500ms).

This problem occurs in Google Chrome. The script doesn't work at all in IE.

I've set up a jsFiddle: http://jsfiddle.net/nZAs4/2/. But since jsFiddle does not support PHP scripts I've taken the privilege to upload it myself to one of my own webhosts. (I've also allowed Access-Control-Allow-Origin).

So how can I get this to work?

解决方案

Since N3rd decided to copy and paste here's mine:

By default, your session variables are not accessible to other scripts until the current script terminates. You'll have to call session_write_close() after you have finished processing the session data in order to persist the data.

This can be done as follows:

  1. start the session
  2. create db entry for this running script
  3. update you session to record the index of this record
  4. close your session for writing session_write_close();
    • this allows your monitoring script to start working
  5. run the processing part of the script (that takes ages) WHILE updating the db entry with its progress

on the monitoring script:

  1. start session (this will hang until the same session in another script has finished/write-closed)
  2. check session for index to job
  3. get the data from the database
  4. show progress
  5. close session

这篇关于使用AJAX检查PHP脚本的进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆