通过ajax为每个项目筛选foreach的PHP打印输出(作为进度条并显示在线过程!


PHP print output of foreach to screen, for each item by ajax (as progress bar and show online process!)

我最近问了同样的问题,但我认为这太难了。https://stackoverflow.com/questions/27659295/

所以我把它改成一个简单的版本:

我有一个php代码:

function callafunction($count){
...do something....
return count;
} 
$count=0;
foreach($rows as $row)
{
echo "<div>";
echo callafunction(++$count);// this function maybe need 10 or more second to proccess
echo "<div>";
}

如何在 HTML 页面中打印结果,其中包含 ajax 的 foreach 的每个循环?可能吗?

例如:

<!-- First Append div without refresh page -->
<div> 1 </div>   // new row
.
.
.
<!-- second Append div without refresh page -->
<div> 1 </div>        // old row
**<div> 2 </div>**    // new row
.
.
.<!-- third Append div without refresh page -->
<div> 1 </div>     //  old row
<div> 2 </div>     //  old row
**<div> 3 </div>** // new row

用 PHP 编写 AJAX 端点,然后调用它并使用 JQuery 更新 DOM。PHP 在页面加载后无法执行此操作。诀窍是在callafunction()函数中包含callback参数。在您的情况下,callafunction()会向生成所需数据的 PHP 页面发起 AJAX 请求。当数据准备就绪时,您可以调用您的卡拉克(这里我称之为writeData())。

function callafunction($count,cb){
  //  do an AJAX request to a PHP file
  //  here i am just mocking it by firing the callback after 1 second
  window.setInterval( function(){
   var mockResult = 'The result for row ' + $count + ' is: ' + Math.random().toString(16);
    cb(mockResult);
  }, 1000 );
}
// the function to write the data once AJAX has returned it
var writeData = function(div,result) {
  div.html(result);
};
$('.row').each(function(){
   var $thisRow = $(this);
   // call the function, which then calls itself every x seconds
   callafunction( $(this).data('rowId'), writeData.bind(null,$thisRow) );   
});
.row {
  width: 200px;
  height: 3em;
  background-color: #eee;
  border: 1px solid gray;
  font-family: verdana;
  font-size: 10px;
  margin: .5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- created by a PHP loop -->
<div class="row" data-row-id="1"></div>
<div class="row" data-row-id="2"></div>
<div class="row" data-row-id="3"></div>