2012-02-29 50 views
3

我想通過Javascript或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或在網站控制器?還是有另一種解決方案?提前致謝。

回答

4

首先,您的$.post調用不會執行您可能期望的操作。這:

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

是一樣的:

$.post "savesort", c 

我覺得你的目的是當異步調用$.post結束,但你需要一個回調函數來執行$('#output').html()。您$.post的這一部分:當$.post呼叫正在興建和它的返回值將是一個jQuery對象,$.post不知道是做什麼用

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

將執行。爲了解決這個問題,只是包裝你的回調,那麼,回調:

$.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反應完全,所以如果它返回任何它不會有問題,退回的東西或重定向。上面的回調變化仍然忽略了控制器返回的結果,但沒關係,:nothing => true是一個明智的做法。

完成所有工作後,您可以通過讓控制器返回要插入頁面的新數據來替換重新加載,然後$.post回調可以將新數據插入到頁面中。這將是一個非常標準的AJAX方法。

+0

這是一些很好的信息,我能夠按照你的解決方案,它的工作。非常感謝,我是Javascript/Jquery/Coffeescript的新手,所以當我將這個從javascript轉換爲coffeescript時必定發生。我知道它的工作原理,並會嘗試你提到的AJAX方法。 – ruevaughn 2012-02-29 19:22:51

2

由於您的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>") 

當然,實際上你會希望它也將更新屏幕的多個相關部分。

這是迄今爲止的首選方式。這隻會對屏幕進行部分更新,並且會對用戶產生最大的響應。

相關問題