0

我真的不知道如何问这个,这就是我在这里问的原因。因此,如果我使用这样的代码:

$.post("/data/something.php", {stuff: 'hi'}, function(data){
$('#box').html(data);
});

通常,如果您有这样的 php,您只会得到 1 个结果:

<?php echo $_REQUEST['stuff'] ?>

我想知道 php 是否有任何方法可以发送一些数据,然后再稍后一点,而不是像这样一次发送所有数据:

<?php 
echo 'Foo';
//Do stuff that takes time
echo 'Bah';
?>
4

3 回答 3

0

有两种方法可以做到这一点。

第一个使用带有flush命令的标准工作流程(http://php.net/manual/en/function.flush.php)。这意味着您可以执行以下操作:

echo "Starting...\n"
flush();
// do long task
echo "Done!\n"

然而:这通常是行不通的。例如,如果您的服务器使用 deflate,则Starting在请求完成之前可能不会发送。许多其他因素也可能导致这种情况(代理、浏览器行为)。

The better option is to use a polling mechanism. Your main script would write its progress to a file (with some session ID related filename), then delete that file when done. You would then add a second script to report the progress in this file (or completion if the file has been deleted) and your JavaScript would send an AJAX request to this checker script (maybe every second or two).

于 2013-03-30T04:35:50.123 回答
0

In PHP

<?php 
    echo 'Foo';
    echo '||||';
    echo 'Bah';
?>

In Javascript

var responses = data.split('||||');

//you will get 
//Foo in responses[0]
//Bar in responses[1]
于 2013-03-30T04:41:12.037 回答
0

I expect that php has no problem doing that (as detailed by @Dave). The complicated part, is for javascript to retrieve the first part of the data, before the transmission completes...

I think what you are asking is answered here: Is it possible for an AJAX request to be read before the response is complete?

The way to accomplish this is by listening on the readyState in the the xhr object. When readyState == 3 it means new content has arrived and you can access it. The technique is referred to as Comet.

and...

So finally, yes it is possible, no it is not easy.

于 2013-03-30T04:43:49.440 回答