如何php将结果立即发送到ajax


How to php send result to ajax immediately

有个问题困扰着我,请帮忙!我使用jquery的ajax来调用phpapi。

$.ajax({
            type:"POST",
            dataType:"json",
            data:{type:type,fid:fid,model:'star'},
            url:'Recommend/Star/mark',
            success:function (data) {
                //do something
            },
        ...
      });

推荐/Star/mark方法中的php代码:

    error_reporting(0);
    set_time_limit(0);
    ob_implicit_flush(true);
    ob_end_clean();
    ob_start ();
    echo json_encode($boolMark);
    ob_flush();
    flush();
    sleep(3);
    $this->afterMark($uid, $fid);

我希望php立即将结果返回到ajax,但我的代码不起作用。

如何让php立即将结果发送到ajax,并继续执行剩余的代码?

 ....
 echo json_encode($boolMark . "<br>'n");
 // get the size of the output
 $size = ob_get_length();
 // send headers to tell the browser to close the connection
 header("Content-Length: $size");
 header('Connection: close');
 ob_end_flush();
 ob_flush();
 flush();
 /******** background process starts here ********/
 ignore_user_abort(true);
 /******** background process ********/
 set_time_limit(0); //no time limit
 /******** Rest of your code starts here ********/

您还需要在flush():之后调用这两个函数

session_write_close(); 
fastcgi_finish_request();