防止ajax进度代码过早中止

时间:2013-04-21 17:07:32

标签: javascript ajax html5

我正在使用index.php

<script type="text/javascript">
    $(function(){
        $("#progressbar").progressbar({
            value: 0 
        });

        function load() {
            $.ajax({
                url: './ajax.php?status='+$( "#progressbar" ).progressbar( "value" ),
                success: function(data) {

                    ajax = eval('(' + data + ')');

                    if(ajax!=false) {
                        $("#progressbar").progressbar({
                            value: ajax.status
                        });

                        $("#message").html( ajax.message );

                        if(ajax.status!=100) {
                            load();
                        }
                    }
                }
            });
        }

        load();
    });
</script>

<div id="message"></div>

用于基于ajax的实时进度信息。这适用于ajax.php:

<?php

    $php_array['status'] = rand(0,99);

  if($php_array['status']>100) {
      $php_array['status'] = 100;
  }

  if($php_array['status'] != 100) {
      $php_array['message'] = 'Aktueller Status <b>'.$php_array['status'].'%</b> von 100%, Differenz: '.(100-$php_array['status']);
  } else {
      $php_array['message'] = 'Juhu endlich geschafft!';
  }


  // Ausgabe des PHP Arrays als JSON Objekt
  echo json_encode($php_array);
?>

在index.php中显示0到99之间的随机数,因此可以正常工作。

我将ajax.php修改为

<?php

  //modified - start
  $zahl = 0;
  $menge = 0;

  if ($handle = opendir('folder')) 
  { 
    while (false !== ($entry = readdir($handle))) 
    {
        if (strpos($entry,$_GET['session_id']) !== false) 
        {                                        
            if (strpos($entry,'result') !== false)
            {
            }
            else
            {
                $zahl += (int)file_get_contents('folder/'.$entry);
                $menge++;        
            } 
        }
    }
    closedir($handle);
  }

  if((int)($zahl/$menge) != 0.0)
  { 
    $php_array['status'] = (int)($zahl/$menge);
  }
  else
  {
    $php_array['status'] = 0;
  }

  //modified - end

  if($php_array['status']>100) {
      $php_array['status'] = 100;
  }

  if($php_array['status'] != 100) {
      $php_array['message'] = 'Aktueller Status <b>'.$php_array['status'].'%</b> von 100%, Differenz: '.(100-$php_array['status']);
  } else {
      $php_array['message'] = 'Juhu endlich geschafft! <img src="http://d4nza.de/blog/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley"> ';
  }
  echo json_encode($php_array);
?>

opendir-part遍历所有输出文本文件,其中只包含0到100之间的数字。目标是查找平均进度。然后在

(int)($zahl/$menge)

它被转换为整数并通过json转发到index.php。

这有时会起作用。这意味着,在index.php上,有时我会看到进度,有时候我没有。

如何使index.php中的代码等待ajax.php响应而不是(可能)过早中止?

0 个答案:

没有答案
相关问题