Rails 4 ajax在提交后没有刷新

时间:2014-10-04 20:35:29

标签: javascript ajax ruby-on-rails-4 crud

我正在使用AJAX将我的项目部分渲染,以便我可以直接在索引页面中创建一个新项目。

现在形式有点作品。我可以创建一个项目,它将被添加到数据库中,但为了查看索引页面上的更改,我必须点击刷新。

我可以直接从索引页面直接销毁这里的代码。我确实尝试重做这个破坏而不是创造,但那是不成功的。

任何建议都会很棒。我试图保持代码相当简单,如destroy函数。

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>

1 个答案:

答案 0 :(得分:0)

试试这个:

删除$('.list-items').prepend("<%= escape_javascript(render(@item)) %>");中的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

在assets / javascripts文件夹中的application.js(或controller_name.js)

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

请勿忘记表单:remote => true标记内的form_for