簡體   English   中英

JavaScript在Rails應用程序中不起作用

[英]Javascript is not working in rails app

我的store.html.erb文件中有此代碼

<%= link_to t('.add_html'), 'javascript:void(0);', 
    :class => "line-item", :product => product.id %>

<script type="text/javascript">

    $('document').ready(function(){
        $(".line-item").click(function(){
            var prod = $(this).attr('product');
            $.ajax({
                url:'<%= line_items_url %>',
                data: {product_id: prod},
                type: 'POST',
                dataType: 'script'
            });
        });

    });
</script>

我的line_items_controller.rb具有此代碼

  def create
    @cart = current_cart
    product = Product.find(params[:product_id])
    @line_item = @cart.add_product(product.id)

    respond_to do |format|
      if @line_item.save
        format.html { redirect_to(store_url) }
        format.js { @current_item = @line_item }
        format.xml  { render :xml => @line_item,
                             :status => :created, :location => @line_item }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @line_item.errors,
                             :status => :unprocessable_entity }
      end
    end
  end

然后我的create.js.erb文件具有以下代碼

$("#notice").hide()
$("#cart").html("<%= j render(@cart) %>")

還有我的_cart.html.erb

<% unless cart.line_items.empty? %>
<div class="cart_title"><%= t('.title') %></div>
<table>
  <%= render(cart.line_items) %>
  <tr class="total_line">
    <td colspan="2">Total</td>
    <td class="total_cell"><%= number_to_currency(cart.total_price) %> </td>
  </tr>
</table>
    <%= button_to t('.checkout'), new_order_path, :method => :get %>
    <%= button_to t('.empty'), cart, :method => :delete,
              :confirm => "Are you sure?" %>

<% end %>

現在,當我單擊“添加到購物車”按鈕時,應將產品添加到購物車中,這應在頁面左側顯示更新的值,但未顯示此值。 但是,當我刷新頁面時,我看到了更新的值。 這意味着我的JavaScript無法正常工作。 請讓我知道為什么我的JavaScript無法正常工作。

您必須在購物車中局部發送@cart作為本地人,並反抗它會動態更新值。

在您的create.js.erb文件中添加此行

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

這應該工作

暫無
暫無

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

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