2016-11-22 20 views
1

我剛剛使用Ajax。我有一個Ruby應用程序,它使用Ajax請求從我的數據庫中刪除一個項目。刷新瀏覽器後,刪除僅在頁面上顯示。我究竟做錯了什麼?由於Ajax調用而導致的更改現在顯示在頁面中,除非我刷新瀏覽器

這裏是與阿賈克斯我再培訓局的文件稱

<script> 
$(document).ready(function(){ 
    $('input[type="checkbox"]').on("change", function() { 
     var hall_id = $(this).val(); 
    $.ajax({ 
    type:"GET", 
    url:"items/" +hall_id , 
    dataType:"json", 
    data: {id: hall_id}, 
    success:function(result){ 
    alert(result); 
    } 
}) 
}); 
}); 
</script> 



<%= link_to "Logout", root_path %> 

<h1>Hello <%= @user.first_name%> <%= @user.last_name%></h1> 

<%= form_for @item do |f| %> 
    <%= f.label :to_do %>: 
    <%= f.text_field :to_do %><br /> 
    <%= f.hidden_field :email, :value => @user.email%> 


    <%= f.submit %> 
<% end %> 

<% @items.each do |item|%> 
    <%if item.email == @user.email%> 
     <%= form_for @item do |f| %> 
      <%= f.check_box :to_do, {}, item.id %> 
      <%= item.to_do%><br /> 
     <% end %> 
    <%end%> 
<%end%> 

這裏是我的控制器

class ItemsController < ApplicationController 
    def index 
    end 

    def new 
    end 

    def show 
    @items = Item.find(params[:id]) 
    Item.destroy(params[:id]) 
    puts @items.email 
    redirect_to :back 
    end 

    def create 
    @item = Item.create(to_do: params[:item][:to_do], email: params[:item][:email]) 
    redirect_to :back 
    end 
end 

回答

0

我覺得現在的問題是

redirect :back 

你必須有迴應您想在包含Items的div上更新HTML部分。

建議開始:

  • 移動銷燬行動,以保持Rails的資源的RESTful架構破壞端點。
  • 更新您的ajax調用,以便使用新的銷燬端點使用的刪除方法。

所以,你的上述ItemsController應該是這樣的:

items_controller.rb

class ItemsController < ApplicationController 
    helper_method :item 
    helper_method :items 

    def index 
    items 
    end 

    def new 
    @item = Item.new 
    end 

    def show 
    item 
    end 

    def create 
    Item.create(item_params) 
    redirect_to item 
    end 

    def destroy 
    item.destroy 

    render 'items/list', items: items 
    end 

    private 

    def item 
    @item ||= Item.find(params[:id]) 
    end 

    def items 
    @items ||= Item.all 
    end 

    def item_params 
    params.require(:item).permit(:to_do, :email) 
    end 
end 

而AJAX調用應該是:

<script> 
    $(document).ready(function() { 
    $('input[type="checkbox"]').on("change", function() { 
     var hall_id = $(this).val(); 

     $.ajax({ 
     type: 'DELETE', 
     url: "items/" + hall_id , 
     dataType: "json", 
     data: { id: hall_id }, 
     success:function(data) { 
      $('.items-container').html(data); 
     } 
     }) 
    }); 
    }); 
</script> 
相關問題