【问题标题】:Rails Ajax query data before reloading pageRails Ajax 在重新加载页面之前查询数据
【发布时间】:2013-10-29 06:52:53
【问题描述】:

所以我正在努力寻找一种更好的方式来刷新页面。我有一个应用程序,它使用您在系统上捕获的数据构建 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 次那样重新加载页面,每次我尝试 reasearch 如果可能的话,我都会得到这个rubyonrails guide,这对于这种边缘情况并没有真正的洞察力。这是否可能,如果可以,是否有任何关于如何做到这一点的好的教程/博客文章/建议?谷歌一无所获。

【问题讨论】:

  • 定期重新加载是您甚至不应该考虑在任何形式的应用程序中使用的东西。它使用户感到困惑并使应用程序不专业(至少恕我直言)。您应该setInterval 在服务器上检查数据是否准备好。如果它已准备好并且用户在同一页面,则只需更新显示结果的视图块。或者在成功完成任务后,显示一个弹出窗口或类似 Linux 的警报,通知用户所述任务已完成。另外,到时候别忘了clearInterval。在警报中,提供一个链接以将用户带到结果。
  • 是的,这就是我正在查看的页面将不得不刷新,因为还有表格也会刷新。但我 100% 同意。吸引我的部分是使用 ajax 查询服务器数据。我正在使用 respond_to |格式|然后 format.js 尝试抓住它,但这很令人困惑

标签: ruby-on-rails ajax coffeescript


【解决方案1】:

所以我最终做的事情很简单。感谢所有帮助。在我的控制器中,我设置了一个 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

然后它会根据您指定的时间间隔查询控制器,并且只有在发生更改时才会重新加载页面。它的代码多一点,然后只是定期重新加载,但用户会喜欢它! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 2013-02-06
    • 2015-12-26
    • 2018-06-07
    • 2014-10-06
    相关资源
    最近更新 更多