我正在尝试通过 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
我也在考虑将 render :nothing => true 更改为 redirect_to root_url 但这似乎也不起作用。
这是我的 Routes.rb(为了空间而缩短)
locksmithing::Application.routes.draw do
get "site/home"
match "/savesort" => 'site#savesort'
root to: 'site#home'
end
那么,我应该在哪里添加刷新页面的代码呢? Javascript 还是在站点 Controller 中?还是有其他解决方案?提前致谢。
最佳答案
首先,您的 $.post
call 不会执行您可能期望的操作。这:
$.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>")
如果您将 window.location.reload(false)
紧跟在 $.post
之后,那么您将在 POST 完成之前重新加载页面,而这可能不是您想做什么,这可以解释您的“订单困惑”问题。尝试将其移动到 $.post
回调中,以便它在 POST 完成后执行:
$.post "savesort", c, ->
$("#output").html("<p id=\"flash_notice\">Saved Successfully</p>")
window.location.reload(false)
您的原始代码完全忽略了来自 SiteController#savesort
的响应,因此无论它什么都不返回、返回某些内容或重定向都无关紧要。上面的回调更改仍然忽略了 Controller 返回的内容,但这没关系,:nothing => true
是明智的做法。
完成所有工作后,您可以通过让 Controller 返回要插入到页面中的新数据来替换重新加载,然后 $.post
回调可以将该新数据插入到页面中.这将是一个非常标准的 AJAX 方法。
关于jquery - 如何使用 Javascript 或 Ruby on rails 重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9495066/