[英]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.