单击表行后更新div的内容

时间:2013-08-25 20:32:13

标签: ruby-on-rails

我有数据表和div,我想在点击数据表的行后用ajax加载有关订单的信息。

资产/ JavaScript的/ orders.js:

$(document).ready(function() {
    $('#orders').dataTable({
        "sPaginationType": "full_numbers",
        "bJQueryUI": true
    });

    $('#orders tbody tr').each( function() {
        this.onclick = function() {
            $('#order_info').load(
                ???
            )
        };
    })

})

订单/ list.html.erb:

    <table id="orders">
      <tbody>
      <% @orders.each do |order| %>
        <tr data-orderrow=<%= order[:id] %>>
        </tr>
      <% end %>

      </tbody>
    </table>

<div id="order_info" style="float: right;">
</div>

如果我的方法很好,我应该把它放在什么地方?在我的javascript中。

1 个答案:

答案 0 :(得分:0)

您可以对某些控制器和返回json数据的操作进行ajax调用。然后使用该数据,并显示返回的json。

$(document).ready(function() {
  // best to 'cache' the jquery queries you use more than once.
  var $orders = $("#orders"),
      $orderInfo = $("#orderInfo");

  $orders.dataTable({
      "sPaginationType": "full_numbers",
      "bJQueryUI": true
  });

  // it is best not to attach one click even to each 'tr', so instead
  //  I've added a single click event to the entire table, and then
  //  determine the closest 'tr' to get the orderId from it. 
  $orders.click(function(e){
    var $target = $(e.target), $order, orderId; // get the element that was clicked
    $order = $target.closest("tr");
    orderId = $order.attr("data-orderrow");

    $.getJSON("/orders/"+orderId+".json",function(orderData){
      // do something with orderData, which is an object with the order data
    });
  });  
})

然后在你的控制器中,你可以做这样的事情。您需要以最适合您应用的方式填写此内容:

class SomeController < ApplicationController
  def show
    order = Order.find(params[:id])

    respond_to do |format|
      format.html { render "show" }
      format.json { render :json => order }
    end
  end
end