jquery的传入数据事件处理程序

I am writing a PHP code to ping a computer from my server. the code is simple but I think the browser is caching the incoming data:

run.php

<?php

    for ($i=0; $i<10; $i++) {
        $host = '127.0.0.1'; 
        $port = 80; 
        $waitTimeoutInSeconds = 1; 
        if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)){   
            // It worked 
            echo "yes, you can access $ip from this server<BR>";
            sleep(1);
        } else {
            // It didn't work 
            echo "nope, you cannot access $ip from this server<BR>";
        } 
        fclose($fp);
    }

?>

index.php

<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
    $.ajax({
        url: 'run.php',
        success: function(data) {
            $('.ping-data').append(data);
        }
    });
</script>
Ping data:
<div class="ping-data" style="border: 1px solid #9f9f9f; width: 600px; min-height: 400px;"></div>

But when I run the code index.php, it waits and echos the whole data once, instead of printing one line of ping per second. How can I catch this event and print the data whenever a line of data is sent?

Just remove loop from PHP file so it executes request only once and add loop to client side (Javascript).

you need to remove the sleep/for from php and create a function in js to intervally ping the server like:

var interval = setInterval(ping, 1000);
var times = 0;
var timestorun = 10;
function ping(){
    if(times < timestorun){
        times++;
    }else{
        clearInterval(interval);
        return false;
    }
    $.ajax({
        url: 'run.php',
        success: function(data) {
            $('.ping-data').append(data);
        }
    });
}

Adding to Class's answer, I recommend adding the cache parameter to the ajax call in order to avoid browser side caching:

var interval = setInterval(ping, 1000);
var times = 0;
var timestorun = 10;
function ping(){
    if(times < timestorun){
        times++;
    }else{
        clearInterval(interval);
        return false;
    }
    $.ajax({
        url: 'run.php',
        cache: false,
        success: function(data) {
            $('.ping-data').append(data);
        }
    });
}

See also jQuery.ajax