Rails 4 ajax更新div

N. *_*hle 2 javascript ajax jquery ruby-on-rails-4

我喜欢使用ajax更新包含新值的表.这是什么想法.我有一个购物车,用户可以在其中更改产品的数量.我不想重新加载整个页面.我想重新加载表格.目前它可以重新加载整个页面.

我做了什么.

我有一个输入数量值的表格.要将产品与购物车(ManyToMany)连接,我使用line_item.因此,每个line_item代表购物车中的产品.

这个购物车的视图

<div id="cart_table">
  <%= render @cart %>
</div>
Run Code Online (Sandbox Code Playgroud)

渲染@cart

<table class="table  table-hover table-condensed">
  <tbody>
    <%= render cart.line_items %>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

具有更新形式的Line_items:

<%= form_tag(line_item_path, method: "put", remote: true, class: "table_form") do %>
  <%= hidden_field_tag("product_id", value = line_item.product.id) %>
  <label>
    <%= number_field_tag "quantity", value = line_item.quantity, in: 1...11 %>
    <%= submit_tag "update", class: "btn btn-mini" %>
  </label>
<% end %>
Run Code Online (Sandbox Code Playgroud)

line_items的控制器:

def update
    @cart = current_cart
    @line_item = @cart.update_product(params[:product_id], params[:quantity])
    respond_to do |format|
        if @line_item.save
            format.html { redirect_to current_cart, notice: 'Changed' }
            format.js
        else
            format.html { render action: "new" }
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

这是我被卡住的地方.我需要在update.js.rjs中添加什么内容?现在我有这条线

$('#cart_table').replaceWith("<%= escape_javascript(render @cart) %>");
Run Code Online (Sandbox Code Playgroud)

但没有任何反应,我在控制台中收到错误:

send 
jQuery.extend.ajax 
$.rails.rails.ajax 
$.rails.rails.handleRemote 
(anonymous function) 
jQuery.event.dispatch 
elemData.handle
Run Code Online (Sandbox Code Playgroud)

很高兴得到一些想法来解决这个小问题.

谢谢

编辑:最好使用

$('#cart_table').html("<%= escape_javascript(render @cart) %>");
Run Code Online (Sandbox Code Playgroud)

在js文件中.

Ole*_*dul 5

尝试使用update.js.erb而不是update.js.rjs