2014-10-04 97 views
1

我使用AJAX渲染我的項目部分,以便我可以直接在索引頁面中創建一個新項目。Rails 4 ajax提交後不刷新

現在形式的作品。我可以創建一個項目並將其添加到數據庫中,但爲了查看索引頁上的更改,我必須進行刷新。

我可以很容易地從索引頁面銷燬,這裏是代碼。我確實試圖重做這個破壞而不是創造,但那是不成功的。

任何建議將是偉大的。我試圖保持代碼非常簡單,像破壞函數。

destroy.js.erb

$('.delete_item').bind('ajax:success', function() { 
     $(this).closest('tr').fadeOut(); 
}); 

這是我的index.html。這只是基本的導軌造型。

<h1>Listing items</h1> 

<table> 
    <thead> 
    <tr> 
     <th>Content</th> 
     <th>Done</th> 
     <th colspan="3"></th> 
    </tr> 
    </thead> 

    <tbody> 
    <% @items.each do |item| %> 
     <tr> 
     <td><%= item.content %></td> 
     <td><%= item.done %></td> 
     <td><%= link_to 'Show', item %></td> 
     <td><%= link_to 'Edit', edit_item_path(item) %></td> 
     <td><%= link_to 'Destroy', item, method: :delete, data: { confirm: 'Are you sure?' }, remote: true, class: 'delete_item' %> </td> 
     </tr> 
    <% end %> 
    </tbody> 
</table> 

<br> 

<div class='new-item'> 
    <%= render 'form' %> 
</div> 

create.js.erb

$('.new-item').html("<%= escape_javascript(render partial: 'items/form', locals: {item: @item}) %>"); 

物品控制器:

class ItemsController < ApplicationController 
    before_action :set_item, only: [:show, :edit, :update, :destroy] 
    respond_to :html, :js 

    # GET /items 
    # GET /items.json 
    def index 
    @items = Item.all 
    @item = Item.new #will rename later to @new_item 
    respond_to do |format| 
     format.html 
     format.json 
     format.js 
    end 
    end 

    # GET /items/1 
    # GET /items/1.json 
    def show 
    end 

    # GET /items/new 
    def new 
    @item = Item.new 
    end 

    # GET /items/1/edit 
    def edit 
    end 

    # POST /items 
    # POST /items.json 
    def create 
    @item = Item.new(item_params) 

    respond_to do |format| 
     if @item.save 
     format.html { redirect_to @item, notice: 'Item was successfully created.' } 
     format.json { render :show, status: :created, location: @item } 
     else 
     format.html { render :new } 
     format.json { render json: @item.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /items/1 
    # PATCH/PUT /items/1.json 
    def update 
    respond_to do |format| 
     if @item.update(item_params) 
     format.html { redirect_to @item, notice: 'Item was successfully updated.' } 
     format.json { render :show, status: :ok, location: @item } 
     else 
     format.html { render :edit } 
     format.json { render json: @item.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /items/1 
    # DELETE /items/1.json 
    def destroy 
    @item = Item.find(params[:id]) 
    @item.destroy 

    respond_to do |format| 
     format.html { redirect_to items_path } 
     format.json { head :no_content } 
     format.js { render layout: false } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_item 
     @item = Item.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def item_params 
     params.require(:item).permit(:content, :done) 
    end 
end 

控制檯日誌:

Started POST "/items" for 127.0.0.1 at 2014-10-04 15:35:55 -0500 
Processing by ItemsController#create as JS 
    Parameters: {"utf8"=>"✓", "item"=>{"content"=>"Eggs", "done"=>"0"}, "commit"=>"Create Item"} 
    (0.1ms) begin transaction 
    SQL (0.4ms) INSERT INTO "items" ("content", "created_at", "done", "updated_at") VALUES (?, ?, ?, ?) [["content", "Eggs"], ["created_at", "2014-10-04 20:35:55.965462"], ["done", "f"], ["updated_at", "2014-10-04 20:35:55.965462"]] 
    (185.1ms) commit transaction 
Redirected to http://localhost:3000/items/17 
Completed 302 Found in 196ms (ActiveRecord: 186.3ms) 


Started GET "/items/17" for 127.0.0.1 at 2014-10-04 15:35:56 -0500 
Processing by ItemsController#show as JS 
    Parameters: {"id"=>"17"} 
    Item Load (0.3ms) SELECT "items".* FROM "items" WHERE "items"."id" = ? LIMIT 1 [["id", 17]] 
    Rendered items/show.html.erb within layouts/application (0.7ms) 
Completed 200 OK in 61ms (Views: 59.4ms | ActiveRecord: 0.3ms) 

編輯1:基於關建議。該項目仍然只顯示刷新後。

def create 
    @item = Item.new(item_params) 
    if @item.save 
     flash[:notice] = "Item was saved" 
    else 
     flash[:error] = "There was an error. Please try again." 
    end 
    respond_with(@item) do |format| 
     format.html {redirect_to @item} 
    end 
    end 

編輯2:仍然沒有工作,但有些更改 create.js.erb

$('.list-items').prepend("<%= escape_javascript(render(@item)) %>"); 
    $('.new-item').html("<%= escape_javascript(render partial: 'form', locals: { item: @item }) %>)"); 

index.html.erb

<div class='list-items'> 
    <%= render 'items', collection: @items%> 
</div> 


<div class='new-item'> 
    <%= render 'form'%> 
</div> 
+0

嘗試在respond_to塊之外保存''@ item.save'',然後用@item的respond_with爲'''format.html''渲染redirir ect選項。 – shayonj 2014-10-05 07:23:22

+0

看看我上面的編輯。我做了更改,但仍然只是刷新顯示。 – 2014-10-05 14:48:58

+1

在您更改爲'create.js.erb'之前,我會說這是問題所在。您正在清空表格,但不會將該項目追加到列表中。現在你的JS似乎正在這樣做(嗯,預先未決)。要進行調試,我會在該文件中添加一個'console.log(「<%= @ item.inspect%>」)或其他內容,以查看它是否被打中。這將在_Web Inspector_控制檯中輸出(即不在上面顯示的「控制檯日誌」標題下的服務器日誌中)。如果這種情況正在發生,那麼我會盡量確保您的JS在鍵入WI控制檯時工作。這應該有助於縮小問題的範圍。 – Sasha 2014-10-06 19:54:53

回答

0

試試這個:

刪除在您的create.js.erb然後添加一個ID到您的表,如<table id="myTable">

在你的控制器

def create 
    @item = Item.new(item_params) 
    if @item.save 
     flash[:notice] = "Item was saved" 
    else 
     flash[:error] = "There was an error. Please try again." 
    end 
    respond_to do |format| 
     format.html {redirect_to @item} 
     format.js {render :inline => "<tr><td><%= @item.content %></td><td><%= @item.done %></td><td><%= link_to 'Show', @item %></td><td><%= link_to 'Edit', edit_item_path(item) %></td><td><%= link_to 'Destroy', @item, method: :delete, data: { confirm: 'Are you sure?' }, remote: true, class: 'delete_item' %></td></tr>"} 
    end 
end 

在你的資產的application.js(或controller_name.js)/ JavaScript的文件夾

$(".list-items").on("ajax:success", function(evt, data, status, xhr) { 
    $('#myTable tbody).append(xhr.responseText);  
}); 

不要忘記:remote => true表單的form_for標籤內