Question:
Let's say there is an ajax
request like this:
$.ajax({
url: "action.php",
success: function (response) {
//какое-то действие здесь
};
});
И action.php
:
<?php
while(true){
//выполняется какая-то логика
echo json_encode(//какие-то данные);
}
?>
Is it possible after each echo
process this data in an ajax
request and wait until the next piece of data arrives?
Answer:
Use a so called comet
:
Server side:
for($i=0; $i < 10; $i++) {
sleep(1);
$arr = array("time" => time());
echo "<script>parent.callback(" . json_encode($arr) . ")</script>";
flush();
ob_flush();
}
On the client side:
<iframe id="comet"></iframe>
<script>
function start() {
document.getElementById('comet').src = 'comet.php';
}
function stop() {
document.getElementById('comet').src = '';
}
function callback(data) {
document.getElementById("div").innerHTML += JSON.stringify(data);
}
</script>
<input type="button" onclick="start()" value="start">
<input type="button" onclick="stop()" value="stop">
<div id="div"></div>