如果不刷新Rails中的浏览器,AJAX请求就无法看到效果



我和这个家伙也遇到了同样的问题

我和他一样把rjs改成了js.erb。我们都使用<%= button_to 'Add to Cart',line_items_path(:product_id => product) ,:remote=>true %>向控制器发送AJAX请求。format.js可以进行微调并执行create.js.erb。但是cart没有添加任何内容。

日志结果:

Rendered line_items/_line_item.html.erb (4.3ms) Rendered carts/_cart.html.erb (8.0ms) Rendered line_items/create.js.erb (8.8ms)

这是我们发送AJAX请求的index.html.erb

<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% @products.each do |product| %>
<div class="entry">
<%= link_to image_tag(product.image_url), line_items_path(:product_id => product), html_options = {:method => :post} %>
    <h3><%= product.title %></h3>
    <%=sanitize product.description %>
    <div class="price_line">
      <span class="price"><%= number_to_currency(product.price,:precision=>3) %></span>
      <%= button_to 'Add to Cart',line_items_path(:product_id => product) ,:remote=>true %>
    </div>
  </div>
<% end %>

这是处理请求的line_items控制器函数

  # POST /line_items
  # POST /line_items.json
  def create
     # for exercise only
    session[:counter] = nil
    @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_index_path }
        format.js
        format.json { render json: @line_item, status: :created, location: @line_item }
      else
        format.html { render action: "new" }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }
      end
    end

  end

create.js.erb

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

我解决了这个问题。感谢这篇伟大的文章,它告诉我firebug查看AJAX请求响应源的能力。JSLint帮助我检查javascript语法。最后,我要感谢Firebug,它是一个非常棒的工具。

问题是,如果出现任何语法错误,则不会执行javascript

在我的问题中:

我应该使用单引号而不是双引号来包装渲染结果。呈现结果显示了许多HTML&";,以及"哪种包装会导致javascript中的语法错误。(不允许在双重quated中双重quate)

所以我只需将$('#cart').html("<%= escape_javascript(render(@cart)) %>");更改为$('#cart').html('<%= escape_javascript(render(@cart))%>');

我希望这个答案能帮助其他同样遭受噩梦般员工痛苦的人。如果可能的话,请帮助我提高问题率:)

让我们使用j()辅助方法:$('#cart').html("<%=j render(@cart)%>");

最新更新