The following PHP class can be used to send the correct responses:
define('MR_MIN_INITIAL_RESPONSE_LENGTH', 1024); class multi_response { private $first_response = true; private $callback_fn; function __construct() { $this->callback_fn = $_REQUEST['callback']; } function send( /* string/object */ $data) { if ($this->first_response) { echo '<html><head></head><body>'; } if (is_object($data)) { $data = json_encode($data); } echo '<script type="text/javascript">'; echo $this->callback_fn,'(',$data,')'; echo '</script>'; $len = strlen($data); if ($this->first_response && $len < MR_MIN_INITIAL_RESPONSE_LENGTH) { echo '<!-- '; for ($i=$len+1; $i<=MR_MIN_INITIAL_RESPONSE_LENGTH; $i++) { echo 'x'; } echo ' -->'; } $this->first_response = false; flush(); } function finish() { echo '</body></html>'; } }
Example usage:
$response = new multi_response(); $response->send(compute_first_result()); $response->send(compute_second_result()); $response->send(compute_third_result()); $response->finish();