簡體   English   中英

在Ruby on Rails中通過Ajax渲染部分視圖

[英]Render a partial view via ajax in Ruby on Rails

目前,我正在嘗試將我的Rails應用程序設為單頁,但是我在局部渲染時遇到了一些問題。.現在這是我的控制器代碼:

class WelcomeController < ApplicationController

    def create
        @welcome = WelcomeController.new
        render :partial => 'enjoy'
    end

    def index
        if params[:id] == 'enjoy'
            @partial_view = 'enjoy'
        elsif params[:id] == 'about'
            @partial_view = 'about'
        else
            @partial_view = 'main'
        end
    end

end

因此,此控制器鏈接到我的視圖,並且要更改頁面,我在index動作中使用了代碼,但是現在我試圖在create動作中使用它。 我試圖調用create動作的index.html.slim的代碼是:

        div id="content"

        = form_tag(:url => {:action => 'create'},
                :update => "content", :position => :bottom,
                :html => {:id => 'subject_form'}, 
                :remote => true)

            = submit_tag 'Add'

因此,在按鈕上單擊“添加”,我期望_enjoy.slim.html中的內容,這是我的部分內容,其ID為“ content”,進入div,但是當單擊按鈕並呈現_enjoy.html.slim時它加載在整個index.html.slim頁面的頂部...所以我被困在那,如何使它加載到特定的div?

非常感謝對這個問題有答案的任何人{:

您必須在“ welcome”視圖目錄中添加一個create.js.erb文件,並且必須在其中渲染每個ajax的局部文件:

$("#content").html("<%= j render(:partial => 'welcome/enjoy') %>");

在控制器的create動作中,您必須響應javascript:

def create
 ...
 respond_to do |format|
   format.js
 end
end

控制器:

class WelcomeController < ApplicationController

  def create
    @welcome = WelcomeController.new
    # Remove the render
  end

  def index
    # No change
  end    
end

視圖:

div id="content"

= form_tag({:action => 'create'}, :id => 'subject_form',  :remote => true) do
  = submit_tag 'Add'

創建welcome / create.js.erb並添加以下行:

$('#content').html("<%= j render(:partial => 'welcome/enjoy') %>")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM