我希望这对你有用
首先,您需要在 PHP 脚本中禁用输出缓冲区
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);
然后您需要在此过程中从 PHP 中回显您的进度,如下所示:
for($i=0;$i < 20;$i++){
echo ($i > 0 ? "#":"").($i/20*100);
sleep(1);
}
然后,在 javascript 中,您需要侦听 xhr readystate 更改事件,当发生这种情况时,只需解析响应文本并根据需要显示进度。
监听事件:
$.ajaxPrefilter(function( options, _, jqXHR ) {
if ( options.onreadystatechange ) {
var xhrFactory = options.xhr;
options.xhr = function() {
var xhr = xhrFactory.apply( this, arguments );
function handler() {
options.onreadystatechange( xhr, jqXHR );
}
if ( xhr.addEventListener ) {
xhr.addEventListener( "readystatechange", handler, false );
} else {
setTimeout( function() {
var internal = xhr.onreadystatechange;
if ( internal ) {
xhr.onreadystatechange = function() {
handler();
internal.apply( this, arguments );
};
}
}, 0 );
}
return xhr;
};
}
});
和ajax请求示例:
$.ajax({
url: "test.php",
cache: false,
onreadystatechange: function( xhr ) {
res = xhr.responseText.split("#");
$("#id").html(res[res.length-1] + "% done<br/>");
}
}).done(function( data ) {
$("#id").append("all done!</br>");
});
});
使用 jQuery 1.5+ 测试