2013-01-09 39 views
0

我知道如何在Sinatra中使用ajax來進行簡單的操作,例如更新一個簡單的文本框或類似的東西:我只需發送一個ajax請求並替換我想要的內容success事件。對我來說很清楚。與Sinatra一起使用ajax來更新表格

但是我應該怎麼做當我有一個表我想更新使用Ajax?在ajax#success上再次「繪製」表格將會非常困難。當然應該有更簡單的方法來實現這一點。

它存在嗎?

回答

2

不是最有效的方式,但是您可以將表格的完整HTML部分返回給Ajax-Request,然後使用表格返回頁面上的Div-Container並返回結果。在大多數情況下,這是最簡單的方法:只交換div的內容。

示例代碼

行動在西納特拉主文件:

# some code 
post "/path/to/your/action" do 
    # get the parameters you need and do the update operation, then: 
    @goods = Good.all # if you use activerecord, or use what you want to get the list 
    slim :goods_table # or haml or erb or ... 
end 
# some code 

您的視圖文件(我將使用超薄這裏爲例):

table 
    tr 
    th title 
    th price 
    th weight 
    th discount 
    - @goods.each do |good| 
    th 
     td = good.title 
     td = good.price 
     td = good.weight 
     td = good.discount 

我假設你的表是放置在ID爲「goods-table」的div中。所以使用jQuery的JS會是這樣的:

$.post("path/to/your/action", {parameter1: x, paramater2: y}, function (data) { 
    $("#goods-table").html(data); 
}); 
+0

我想我已經從阿賈克斯#調用成功「部分(table_content_partial」)渲染表。我該怎麼做? – Alexandre

+0

你使用jQuery或痛苦的普通的JavaScript? – Hisako

+0

我可以使用任何東西,沒關係。那麼我是否會從Sinatra方法中返回「已完成的HTML表格部分」? – Alexandre