繁体   English   中英

如何使用Javascript或Ruby on rails重新加载页面

[英]How to make page reload with Javascript, or Ruby on rails

我试图通过Javascript或Ruby on Rails代码对新位置进行排序后重新加载页面。

$("#serialize").click ->
c = set: JSON.stringify($("#sortable").nestedSortable("toHierarchy",
  startDepthCount: 0
))
$.post "savesort", c, $("#output").html("<p id=\"flash_notice\">Saved Successfully</p>")
false

我想在这里添加它

$.post "savesort", c, $("#output").html("<p id=\"flash_notice\">Saved Successfully</p>")
window.location.reload(false); 
false

但似乎搞砸了订单。 这是我的rails代码

class SiteController < ApplicationController

def savesort
neworder = JSON.parse(params[:set])
prev_item = nil
neworder.each do |item|
  dbitem = Category.find(item['id'])
  prev_item.nil? ? dbitem.move_to_root : dbitem.move_to_right_of(prev_item)
  sort_children(item, dbitem) unless item['children'].nil?
  prev_item = dbitem   
end
Category.rebuild!
render :nothing => true
  end
end

我也在考虑改变渲染:没有=>对redirect_to root_url是真的,但这似乎也不起作用。

这是我的Routes.rb(为空间而缩短)

locksmithing::Application.routes.draw do
  get "site/home"
  match "/savesort" => 'site#savesort'
    root to: 'site#home'
end

那么,我应该在哪里添加代码来刷新页面? Javascript还是在站点控制器中? 还是有另一种解决方案? 提前致谢。

首先,你的$.post调用没有做你可能期望的那样。 这个:

$.post "savesort", c, $("#output").html("<p id=\"flash_notice\">Saved Successfully</p>")

与此相同:

$.post "savesort", c

我认为你的意图是在异步$.post调用完成时执行$('#output').html()但你需要一个回调函数。 $.post这一部分:

$("#output").html("<p id=\"flash_notice\">Saved Successfully</p>")

将在构建$.post调用时执行,其返回值将是一个jQuery对象, $.post将不知道该怎么做。 要解决这个问题,只需将回调包装在回调函数中:

$.post "savesort", c, ->
    $("#output").html("<p id=\"flash_notice\">Saved Successfully</p>")

如果你在$.post之后立即放置了window.location.reload(false) ,那么你将在POST完成之前重新加载页面,这可能不是你想要做的,这可以解释你的“混乱的订单”问题。 尝试将其移动到$.post回调中,以便在POST完成执行:

$.post "savesort", c, ->
    $("#output").html("<p id=\"flash_notice\">Saved Successfully</p>")
    window.location.reload(false)

您的原始代码完全忽略了SiteController#savesort的响应,因此如果它没有返回任何内容,返回内容或重定向,则无关紧要。 上面的回调更改仍然忽略控制器返回的内容但是没关系:nothing => true对它:nothing => true是明智的。

一旦完成所有工作,就可以通过让控制器返回要插入页面的新数据来替换重新加载,然后$.post回调可以将新数据插入到页面中。 这将是一个非常标准的AJAX方法。

由于您post到服务器,您的服务器可以发送一小部分,仅重新呈现更改的页面部分。

调整控制器操作,而不是声明任何渲染/重定向操作:

class SiteController < ApplicationController

  def savesort
    neworder = JSON.parse(params[:set])
    prev_item = nil
    neworder.each do |item|
      dbitem = Category.find(item['id'])
      prev_item.nil? ? dbitem.move_to_root : dbitem.move_to_right_of(prev_item)
      sort_children(item, dbitem) unless item['children'].nil?
      prev_item = dbitem   
    end
    Category.rebuild!
  end
end

现在,这将查找名为savesort.js.erb的默认视图。 在该视图中,您可以执行任何操作来覆盖类别列表。

此文件包含在浏览器中执行的纯javascript,例如:

$("#output").html("<p id=\"flash_notice\">Saved Successfully</p>")

当然,实际上你会希望它也会更新屏幕的更多相关部分。

到目前为止,这是首选方式。 这只会对屏幕进行部分更新,并且会对用户产生最敏感的响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM