繁体   English   中英

每次迭代后更新ajax php foreach循环

[英]ajax php foreach loop update after each iteration

我想做的是使用jQuery / Ajax向PHP脚本发出请求,并在每次foreach循环完成时返回状态更新。 我想使用输出来制作进度条。

我遇到的问题是jQuery仅在整个脚本完成后才更新页面。 有没有一种方法可以强制jQuery或PHP在每个循环中输出,而不仅仅是将其全部转储到success函数中。

        jQuery(document).ready(function($) {            
            $(document).on('click','#fetch-snowfall-data a',function () {
              $(this).text('Fetching Snowfall Data...');
                $.ajax({
                    type: "GET",
                    async: true,
                    url: "url.php",  
                    data:{},                
                    dataType: "html", 
                    success: function(response){
                        $("#response_container").append(response);
                        $('#fetch-snowfall-data a').text('Fetch Snowfall Data');
                    }
                }); 
            return false;
            });
        });

PHP

foreach ( $results['resorts'] as $resort ) {

    //Do all the things here

    $count++;
    echo $count .'/'. $results['total_rows'];

}

感谢大家的帮助。 我最终设法使这一切正常工作,并将准确分享我的做法,以使其他人将来受益。

共有3个文件-正在加载的页面,处理脚本和侦听脚本。

您将需要知道要处理多少行才能使所有工作正常进行。 我从php变量$results['total_rows'];加载我的$results['total_rows']; 在loading.php中

Loading.php

       jQuery(document).ready(function($) {
            setTimeout(getProgress,1000);
            $(document).on('click','#fetch-snowfall-data a',function () {
              $(this).text('Fetching Snowfall Data...');
                $.ajax({
                    url: 'process.php',
                    success: function(data) {
                        $("#response_container2").append(data);
                    }
                });
                setTimeout(getProgress,3000);
            return false;
            });
            function getProgress(){
                $.ajax({
                    url: 'listen.php',
                    success: function(data) {
                        if(data<=<?php echo $results['total_rows']; ?> && data>=1){
                            console.log(data);
                            $('#response_container').html('<div id="progress"><div class="progress-bar" role="progressbar" style="width:'+ (data / <?php echo $results["total_rows"] ?>)*100 +'%">'+ data + '/' +<?php echo $results["total_rows"] ?> +'</div></div>');
                            setTimeout(getProgress,1000);
                            console.log('Repeat');
                        } else {
                            $('#fetch-snowfall-data a').text('Fetch Snowfall Data');
                            console.log('End');
                        }
                    }
                });
            }
        });

Process.php

foreach ( $results['resorts'] as $resort ) { 

    //Do all the things here you want to.

    $count++;
    session_start();
    $_SESSION['progress'] = $count;
    $_SESSION['total'] = $results['total_rows'];
    session_write_close();
    sleep(1);
}

unset($_SESSION['progress']);

Listen.php

session_start();
echo (!empty($_SESSION['progress']) ? $_SESSION['progress'] : '');

if (!empty($_SESSION['progress']) && $_SESSION['progress'] >= $_SESSION['total']) {
    unset($_SESSION['progress']);
}

进度栏的一些CSS

#progress {
    height: 20px;
    margin-bottom: 20px;
    /* overflow: hidden; */
    background-color: #f5f5f5;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
    box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
}
.progress-bar {
    float: left;
    width: 0;
    height: 100%;
    font-size: 12px;
    line-height: 20px;
    color: #fff;
    text-align: center;
    background-color: #337ab7;
    -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
    box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
    -webkit-transition: width .6s ease;
    -o-transition: width .6s ease;
    transition: width .6s ease;
}

正如adeneo所建议的,我认为您不能返回部分内容。 我试图对此进行研究,但无济于事。 但是,如果有人可以纠正我,我将不胜感激。

对我来说,最终结果是执行递归ajax。

JavaScript的

var data = '';
$(document).on('click','#fetch-snowfall-data a',function () {
  ajaxCall(0);
});

function ajaxCall(num) {
  $.ajax({
    type: "POST",
    async: true,
    url: "url.php",
    data: num,
    dataType: "json",
    xhr:function(){
        //progress bar information here.
    },
    success: function(response) {
      $("#response_container").append(response['data']);
      if (response['check'] === 'next') {
        var nextNum = num +1;
        data += response['data'];
        ajaxCall(nextNum); //call itself for the next iteration
      }else if (response['check'] === 'done'){
        data = response['data'];
        //do stuff with the data here.
      }else if (response['check'] === 'error') {
        return response['data'];
      }
    },
    error:function(xhr, status,error){
        //error information here
    }
  });
}

对于PHP:

只要确保您在json中输出带有两个信息的内容即可。 Json.check :查看是否要移入下一个迭代,完成并输出数据或报告错误。 Json.data输出所需的任何数据。 您需要做的是一次输出每个报告而没有foreach循环

- 编辑 -

我发现了有关php流的一些话题

  1. http://www.sitepoint.com/php-streaming-output-buffering-explained/
  2. 在PHP中(跨平台)实时数据流的最佳方法?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM