我使用以下JS从Rails应用程序的控制器方法中检索一些JSON数据:
$.ajax({
xhr: function() {
var xhr = $.ajaxSettings.xhr();
xhr.onprogress = function(e) {
if (e.lengthComputable) {
console.log(e.loaded / e.total);
}
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
console.log(e.loaded / e.total);
}
};
return xhr;
},
cache: false,
url: '/get_data',
method: 'GET',
dataType: 'JSON',
success: function(data) {
console.log(data);
}
});所述方法如下:
def get_data
@data = [{....}]
respond_to do |format|
format.html
format.json do
response.headers['Content-Length'] = @data.to_s.length.to_s
render json: @data
end
end
end该方法可能需要3-4秒才能返回,因为@data要么很大,要么需要先进行复杂的计算,所以我想在AJAX发生的同时显示一个进度条。
注意:我不仅仅想展示一个显示AJAX之前和之后的加载器,而是实际显示进度!
然而,我发现lengthComputable总是假的……
如何让Rails返回正确的进度?我已经添加了Content-Length头,但它从未出现在响应中...
发布于 2016-10-06 00:56:30
我错了。这不是一个真正的进度条,但它的想法是这样的:
$(function() {
var pg = 0;
function progressbarAdd(){
pg++;
$('#bar').progressbar('option', 'value', pg).children('.ui-progressbar-value').css('display', 'block');
}
$('#bar').progressbar({ value: 0 });
$(document).on({
ajaxStart: function(){
timer = setInterval(function(){
progressbarAdd()
}, 100);
},
ajaxStop: function(){
clearTimeout(timer);
$('#bar').progressbar('option', 'value', 100);
}
});
$.ajax({
method: 'GET',
url:'https://viacep.com.br/ws/01001000/json/',
dataType: 'json',
success: function() {
console.log('JSON:', arguments[0]);
},
error: function() {
console.log('Fail');
}
});
});<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/black-tie/jquery-ui.css" />
</head>
<body>
<div id="bar"></div>
</body>
</html>
发布于 2016-10-05 20:33:57
ProgressEvent.lengthComputable只读属性是一个布尔标志,它指示ProgressEvent所关注的资源是否具有可以计算的长度。
这意味着它需要一个content-length头。要知道资源有多大。您可能正在做的是发送一个不知道大小的application-octet流
发布于 2016-10-05 20:44:12
使用jQuery了解请求何时完成。
$(document).on({
ajaxStart: function(){
//show or create the progress bar
},
ajaxStop: function(){
//hide or remove the progress bar
}
});https://stackoverflow.com/questions/39874012
复制相似问题