簡體   English   中英

Rails 4 Ajax更新div

[英]Rails 4 ajax update div

我喜歡使用ajax用新值更新表。 有什么想法。 我有一個購物車,用戶可以在其中更改產品數量。 我不喜歡重新加載整個頁面。 我想重新加載桌子。 目前,它可以重新加載整個頁面。

我做了什么。

我有一個輸入數量值的表格。 要將產品與購物車(ManyToMany)連接,我使用line_item。 因此,每個line_item代表購物車中的產品。

購物車的此視圖

<div id="cart_table">
  <%= render @cart %>
</div>

渲染@cart

<table class="table  table-hover table-condensed">
  <tbody>
    <%= render cart.line_items %>
  </tbody>
</table>

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 %>

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

這是我卡住的地方。 我必須在update.js.rjs中放入什么? 現在我有這條線

$('#cart_table').replaceWith("<%= escape_javascript(render @cart) %>");

但是什么也沒發生,我在控制台中看到一個錯誤:

send 
jQuery.extend.ajax 
$.rails.rails.ajax 
$.rails.rails.handleRemote 
(anonymous function) 
jQuery.event.dispatch 
elemData.handle

希望能有一些想法來解決這個小問題。

謝謝

編輯:最好使用

$('#cart_table').html("<%= escape_javascript(render @cart) %>");

在js文件中。

嘗試使用update.js.erb而不是update.js.rjs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM