我最近提出同样的问题,但我认为这太难了。 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>";
}
如何通过ajax的每个foreach循环在html页面中打印结果? 有可能吗?
例如:
<!-- 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
答案 0 :(得分:1)
在PHP中编写AJAX端点,并使用JQuery调用它并更新DOM。页面加载后PHP无法执行此操作。诀窍是在callback
函数中包含callafunction()
参数。在您的情况下,callafunction()
会向生成所需数据的PHP页面发起AJAX请求。数据准备就绪后,你可以调用你的callack(我称之为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) );
});
&#13;
.row {
width: 200px;
height: 3em;
background-color: #eee;
border: 1px solid gray;
font-family: verdana;
font-size: 10px;
margin: .5em;
}
&#13;
<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>
&#13;