jQuery.ajax
({
url: ajaxurl,
type: "POST",
xhr: function()
{
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener( 'progress', function( e )
{
if( e.lengthComputable )
{
// Append progress percentage.
var loaded = e.loaded;
var total = e.total;
var progressValue = Math.round( ( loaded / total ) * 100 );
// Bytes received.
jQuery( '.recievedValue' ).html( '' );
jQuery( '.recievedValue' ).append( formatFileSize( loaded ) + ' / ' );
// Total bytes.
jQuery( '.totalValue' ).html( '' );
jQuery( '.totalValue' ).append( formatFileSize( total ) );
// Percentage.
progressElement.find( 'input' ).val( progressValue ).change();
}
}, false );
return xhr;
},
success: function( data )
{}
});
这是我的ajax函数。我可以获得加载的字节数、总字节数和百分比值。但我还需要获取剩余时间和上传文件速度(kb/秒)。有什么办法可以得到这两个值。任何帮助将不胜感激。
最佳答案
尝试这样的事情,它应该会让你走向正确的方向:
虽然最终的代码会以不同的方式进行清理/组织,但我会让我的答案易于您最初的问题识别,这样更容易联系起来。
jQuery.ajax({
url: ajaxurl,
type: "POST",
xhr: function(){
var xhr = new window.XMLHttpRequest();
var started_at = new Date();
xhr.upload.addEventListener( 'progress', function( e ){
if( e.lengthComputable ){
// Append progress percentage.
var loaded = e.loaded;
var total = e.total;
var progressValue = Math.round( ( loaded / total ) * 100 );
// Bytes received.
jQuery( '.receivedValue' ).html( '' );
jQuery( '.receivedValue' ).append( formatFileSize( loaded ) + ' / ' );
// Total bytes.
jQuery( '.totalValue' ).html( '' );
jQuery( '.totalValue' ).append( formatFileSize( total ) );
// Time Remaining
var seconds_elapsed = ( new Date().getTime() - started_at.getTime() )/1000;
var bytes_per_second = seconds_elapsed ? loaded / seconds_elapsed : 0 ;
var Kbytes_per_second = bytes_per_second / 1024 ;
var remaining_bytes = total - loaded;
var seconds_remaining = seconds_elapsed ? remaining_bytes / bytes_per_second : 'calculating' ;
jQuery( '.timeRemaining' ).html( '' );
jQuery( '.timeRemaining' ).append( seconds_remaining );
// Percentage.
progressElement.find( 'input' ).val( progressValue ).change();
}//if
}, false );
return xhr;
},
success: function( data ){}
});
<小时/>
补充(HTML 和 JavaScript)
尽管原始问题没有提供随附的 HTML 或 formatFileSize()
函数,但以下是每个函数的假设基本定义。
HTML
<div id="progressElement">
<div>
<span class="receivedValue"></span>
<span class="totalValue"></span>
</div>
<input name="percentage"/>
<div class="timeRemaining"></div>
</div>
JavaScript
var progressElement = document.getElementById('progressElement');
function formatFileSize(bytes){
// You can make this into something that intelligently outputs B,KB,MB,etc...
return `${Math.round(bytes/1024)}KB`;
}
关于javascript - 获取剩余时间和上传文件速度 - ajax jquery/js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28893154/