2013-01-09 40 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