[英]Update progress bar in rails using jQuery
I'm a complete novice in JavaScript/jQuery and I believe it's a very simple question; 我是JavaScript / jQuery的新手,我相信这是一个非常简单的问题; however I'm not being able to accomplish it.
但是我无法完成它。
I have an asynchronous task being performed (by sidekiq
) and it's progress is available by a method from the model ( percentage_complete
) that retrieves its progress from Redis. 我有正在执行的异步任务(由
sidekiq
)和它的进步是通过提供从模型的方法( percentage_complete
)检索从Redis的进度。
I want to display a progress bar in model's show
view, and I want it to update every x seconds using AJAX. 我想在模型的
show
视图中显示进度条,并希望它使用AJAX每隔x秒更新一次。
The progress bar is being displayed like this on the show.html.erb
file: 进度条将显示在
show.html.erb
文件中,如下所示:
<div class="progress">
<div class="bar" style="width: <%= @model.percentage_complete %>%;"></div>
</div>
How can I set a jQuery script to update this attribute asynchronously? 如何设置jQuery脚本以异步更新此属性?
EDIT 编辑
I also have aa :status
attribute which is set do "done"
when the task is complete. 我还具有一个
:status
属性,该属性设置为在任务完成时执行"done"
。 I would like to stop updating when that happens. 发生这种情况时,我想停止更新。
By reading my question it appears that I haven't tried nothing and just want someone to write the code for me. 通过阅读我的问题,看来我什么都没做,只是希望有人为我编写代码。 Let me add some comments:
让我添加一些评论:
setInterval
to update the attribute every "x" seconds setInterval
每隔“ x”秒更新一次属性 $('.progress .bar').width(<%= @model.percentage_complete %>%)
to set the new percentage $('.progress .bar').width(<%= @model.percentage_complete %>%)
来设置新的百分比 However, since I'm not familiar to jQuery and JavaScript, specially in Rails, I'm not sure if this script should be loaded in a view, or if it should be a view itself. 但是,由于我对jQuery和JavaScript并不熟悉,尤其是在Rails中,因此我不确定该脚本是否应该在视图中加载,或者它是否应该是视图本身。
I solved it by creating an action to retrieve the status 我通过创建一个操作来解决状态来解决它
# GET /status/1.json
def status
@batch = Batch.find(params[:id])
respond_to do |format|
format.json
end
end
and using the following JavaScript: 并使用以下JavaScript:
<script type="text/javascript">
function progress(){
var progress = setInterval(function() {
var $bar = $('.bar');
var $pct = $('#pct');
$.get("<%= @batch.id %>/status.json", function(data){
if (data.status == "done") {
location.reload();
} else {
$bar.width(data.progress+"%");
$pct.text(data.progress+"%");
}
});
}, 800);
}
$(document).ready(function() {
$.get("<%= @batch.id %>/status.json", function(data) {
if (data.status == "processing") {
progress();
}
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.