如何使用Ajax从数据库获取更新值并将其显示在页面上
我有一个Rails表单,可以从Google电子表格中远程导入某些产品.这样做时,它会通过将导入开始时的company.import_status设置为"started",并在完成后将其"finish"来更新制造这些产品的公司.
I have a rails form that imports remotely some products from a google spreadsheet. While doing so, it updates company that makes those products by setting its company.import_status to "started", when the importing starts, and "finish", once it's done.
我有一个显示company.import_status的页面,我尝试对其进行更新,以便可以看到导入何时开始以及何时完成.我的代码如下:
I have a page that shows company.import_status, and I try to update it so I can see when an import starts and when it's finished. My code looks like this:
$(document).ready(function(){
<% @companies.each do |company| %>
setInterval(function(company){
$.ajax({
type : 'GET',
url : 'import',
dataType : 'html',
success : function(company){
$("#company_<%=company.id%>").html("<%= escape_javascript(Company.where(id: company.id).first.import_status) %>");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error!');
}
});
}, 1000);
<% end %>
});
由于某些原因,该字段未更新.它以开始"开始,并一直保持这种状态.我可以更改些什么来解决此问题?如果我尝试通过控制台获取它,它将为我提供正确的值.
For some reason, the field doesn't get updated. It starts off as "started" and just stays that way. What can I change to fix this? If I try getting it through console, it gives me the correct value.
更新:
这是我的导入方法
def import
@companies = Company.find(params[:company].values.map{ |c| c[:id] }.compact)
@companies.each do |company| company.key = params[:company].values.select {|c| c[:id] == company.id.to_s}.first[:file] if !company.import_in_progress? company.import_start
end
end
respond_to do |format|
format.html { redirect_to admin_import_index_path }
format.js
end
end
发生的事情是,ruby代码首先被编译并进行了硬编码,所以当javascipt发生时,ruby中最初设置的内容保持不变.这就是为什么我不断入门"的原因.这是我改用的方法:
What was happening is that ruby code got compiled and kind of hardcoded first, so when javascipt took place, whatever was initially set in ruby stayed that way. That-s why I kept getting "started". This is what approach I used instead:
$(document).ready(function(){
setInterval(function() {
$.get("/companies.json", function(data){
$.each(data, function(index, c) {
var field = "#company" + "_" + c["id"];
$(field).html(c["import_status"]);
console.log(field);
});
});
}, 5000);
});