开发者

Page not updating when using jquery/ajax

开发者 https://www.devze.com 2023-04-11 16:54 出处:网络
I\'m making a web app that lets people add courses to a shopping cart. I have a Cart model that has_many LineItems.

I'm making a web app that lets people add courses to a shopping cart. I have a Cart model that has_many LineItems.

In the cart, I have an ajaxified button that lets people remove individual line items. This works fine. Here's the code for that:

_line_item.html.erb:

<div class="delete_line_item"><%= button_to 'Delete', line_item, 
{:method => :delete, :remote => true} %></div>

The line_items controller:

  def destroy
    @user = current_user
    @line_item.destroy
    @cart = @user.cart

    respond_to do |format|
      format.html { redirect_to(root_path) }
      format.js
      format.xml  { head :ok }
    end
  end

Then, the destroy.js.erb file, located within my views/line_items folder:

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

I want to do something similar for emptying out the cart. To do this, I'm using the update action in the carts controller. Here are the corresponding code chunks for this:

<div class="empty_cart"><%= button_to 'Empty cart', cart, {:method => :put, :remote => true, 
:confirm => 'Are you sure?'} %></div>

#carts controller
  def update
    if @cart.line_items
      @cart.line_items.each do |item|
        item.destroy
      end 
    end 

    respond_to do |format|
      if @cart.update_attributes(params[:cart])
        format.html { redirect_to(root_path, :notice 开发者_运维知识库=> 'Cart emptied.') }
        debugger
        format.js
        format.xml  { head :ok }

Finally, here's the update.js.erb file I've placed within my views/carts folder:

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

The problem is that when I try to empty the cart, the request goes through (in that when I refresh the page, the cart is empty), but the change doesn't appear immediately upon clicking. This makes me think that my browser is simply not rendering the .js.erb file. Do I need to place the update.js.erb file in a different folder or rename it? Or something else going on?


Instead of using the update action, why don't you just use the destroy action for the cart instead of using the update? That's what I did, and it worked.

0

精彩评论

暂无评论...
验证码 换一张
取 消