Javascript在Rails应用程序中不起作用 [英] Javascript is not working in rails app

查看:103
本文介绍了Javascript在Rails应用程序中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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 文件具有此代码

And then my create.js.erb file has this code

$("#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无法正常工作.

Now when I click add to cart button products should be added in the cart and this should show the updated value in the left side of page but it is not showing this. But when I refresh the page I see the updated value. That means my javascript is not working. Please let me know why my javascript is not working.

推荐答案

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

Add this line in your create.js.erb file

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

这应该有效

这篇关于Javascript在Rails应用程序中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆