簡體   English   中英

Ruby on Rails-同時調用html.erb和js.erb

[英]Ruby on Rails - Call both html.erb and js.erb

我的目標是使用相同的控制器調用html.erb和js.erb文件,但它僅調用我的html文件。
我的js沒有被調用。
controller / categories_controller.rb

  def index
    respond_to do |format|
      format.html
      format.js
    end
    @categories = Category.order('name ASC')
    @category = params[:category]
end

查看/類別/index.html.erb

<% @categories.each do |c| %>
  <%= link_to c.name, show_category_path(category: c.id), :id => "btn-filter#{c.id}" %>
<% end %>

views / categories / index.js.erb(問題在這里,未調用此文件)

alert("test");
$("#btn-filter<%=@category%>").attr("class","active");

控制器以請求所要求的格式進行響應,因此,您的鏈接要求使用HTML而不是JS,因此控制器以.html.erb響應。 如果添加呼叫,如下所示:

<%= link_to c.name, show_category_path(category: c.id), :id => "btn-filter#{c.id}", remote: true %>

您的請求將要求JS(因為remote: true屬性),並且控制器將以.js.erb響應。

You should add remote: true option

<% @categories.each do |c| %>
  <%= link_to c.name, show_category_path(category: c.id),remote:true, :id => "btn-filter#{c.id}" %>
<% end %>

它將自動找到index.js.erb文件。

只需向link_to添加一個remote:true屬性。

暫無
暫無

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

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