内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我使用jquery的ajax来调用php api:
$.ajax({
type:"POST",
dataType:"json",
data:{type:type,fid:fid,model:'star'},
url:'Recommend/Star/mark',
success:function (data) {
//do something
},
...
});
Recommend/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);
我想立即向ajax发送php echo结果,但我的代码不起作用。
如何让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 ********/
你希望你的代码在发送响应后在“后台”运行,为此你需要这样做:
// Destroy the current buffer (Just in case...)
ob_clean();
// Start a new buffer
ob_start();
// Send your response.
echo json_encode($boolMark);
// Disable compression (in case content length is compressed).
header("Content-Encoding: none");
// Set the content length of the response.
header("Content-Length: ".ob_get_length());
// Close the connection.
header("Connection: close");
// Flush all output.
ob_end_flush();
ob_flush();
flush();
这会发送完整的标头并关闭连接,否则你的连接将保持活动状态,浏览器将等待php脚本终止其执行。