0

所以我试图找到一种更好的方法来刷新页面。我有一个应用程序,它使用您在系统上捕获的数据构建 Excel 电子表格。所以我所做的只是每 10 秒重新加载一次页面,直到它完成,以便可以正确显示通知。

像这样的东西(它在 HAML 语法中)

.pending_downloads
  - if downloads_policy.pending?
    .notification_notice
      = image_tag 'spinner.gif'
      Your data download is being prepared. This should only take a few minutes. It is safe to leave this page and return later.
      = link_to "Cancel download.", download_path(downloads_policy.pending), :method => :delete, :class => "delete_link"
    = javascript_tag("ToolkitApplication.periodical_reload();")

periodical_reload();方法的 Ajax(在 coffeescript 中)如下所示:

class @ToolkitApplication
  this.periodical_reload = () ->
    setInterval (->
      window.location.reload()
    ), 10000

这种方法我觉得可以做得更好。我想让 ajax 每 3 秒查询一次模型,以查看对象状态何时更改,然后一旦更改,它将重新加载窗口。因此,在下载准备好之前,您不会像 10 次那样重新加载页面,每次我尝试重新搜索是否可能时,我都会得到这个ruby​​onrails 指南,它对这种边缘情况并没有真正的洞察力。这是否可能,如果可以,是否有任何关于如何做到这一点的好的教程/博客文章/建议?谷歌一无所获。

4

1 回答 1

0

所以我最终做的很容易。感谢所有帮助。在我的控制器中,我设置了private一种检查状态的方法

def any_uploads_status_changes?
  return true if !Upload.exists?(params[:id])
  return true if Upload.find(params[:id]).status
end

然后在控制器中设置另一个调用,称为 status:

def status
  if any_uploads_status_changes?
    render :text => 'window.location.reload();'
  else
    render :nothing => true
  end
end

然后设置一个ajax请求方法(它在coffeescript语法中)->

this.periodically_send_ajax_request = (url, method, interval) ->
  setInterval (->
    $.ajax
      url: url
      type: method
      success: (result) ->

  ), interval

然后在视图中使用 js 调用这个请求的条件:

:javascript
  ToolkitApplication.periodically_send_ajax_request("#{status_download_path(:id => downloads_policy.pending.id, :class => @model_class).html_safe }",'get', 2000);

只需确保控制器操作的路径存在

resources :downloads, :only => [:show, :destroy] do
  member do
    get :status
  end
end

然后你去那里它会根据你指定的时间间隔查询控制器,只有当有变化时它才会重新加载页面。它的代码多一点,然后只是定期重新加载,但用户会喜欢它!:)

于 2013-10-30T08:59:12.837 回答