[PHP] Comet with PHP+iframe

PHP 2009. 7. 5. 14:50



Reverse Ajax 기술 중 Comet 이란 걸 PHP와 iframe 으로 구현한 것.
원본출처 : http://www.zeitoun.net/articles/comet_and_php/start


대략 아래와 같은 형태다.







원본출처에 가보면 완벽한 버전의 예제와 댓글들이 있고,
아래는 스스로 구현해 본 가장 간단한 예제다.
서버의 시간을 실시간으로 index.html 에 표시한다.


index.html
 - 클라이언트 브라우저에서 호출하는 페이지. onload 시 backend.php 를 호출할 iframe을 생성한다.

<html>
<head>

<script type="text/javascript">
window.onload = function () {
    document.getElementById("comet").innerHTML = "<iframe id='comet_iframe' src='./backend.php'></iframe>";
}
</script>
</head>

<body>
<span id="debug"></span>
<div id="comet" style="display: none;"></div>
</body>
</html>





backend.php
  - 무한루프로 parent의 debug라는 id를 가진 span의 텍스트노드를 갱신한다. interval은 1초.

<?php
while (true) {
    echo '<script type="text/javascript">';
    echo 'window.document.body.innerHTML = "";';
    echo 'window.parent.document.getElementById("debug").innerHTML="'.date("Y-m-d h:i:s").'";';
    echo '</script>';
    flush();

    sleep(1);
}
?>





Posted by bloodguy
,