我在show.html.erb
页面有以下脚本,以更新我的进度栏。但是它使用jQuery,并且由于jQuery只是在我的application.html.erb
布局的末尾加载,所以我无法在我的页面上使用它。所以我需要在脚本代码之前在我的show.html.erb
页面上。将脚本从页面迁移到Rails中的js文件
很明显,这是不正确的做法。我应该在哪里放置我的脚本代码,以便它为此页面加载?另一个问题是它使用来自控制器的信息(@batch
)。如果我将它移动到我的资产文件夹中的js文件,我该如何访问它?
下面的代码放置在show.html.erb
<%= javascript_include_tag "application" %>
<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>
编辑
年底由于现在我越来越BATCH_ID,我可以检查它是否存在运行代码:
$(document).ready(function() {
var batch_id = $("#batch").data("batch-id");
if (batch_id != null) {
$.get(batch_id + "/status.json", function(data) {
if (data.status == "processing") {
progress();
}
});
}
});
是否确定为代码在每一页上运行,即使没有进度条?或者我应该限制它到我的节目视图?如果我应该限制它,我该怎么做? :) –
看来我的编辑解决了这个问题,对吧? ;) –
是的,应该这样做。关于为这个单独的页面加载jquery ......我不知道最佳做法是什么。也许值得另一个问题 – mihai