簡體   English   中英

在嘗試呈現AJAX響應時“缺少此請求格式和變體的模板。”

[英]“missing a template for this request format and variant.” when trying to render AJAX response

我正在嘗試使用select_tag來過濾漢字單詞列表。 我的想法是當用戶從下拉菜單中選擇選項 - >自動提交表單 - >使用AJAX來獲取search_by_lesson操作並將數據填充到#kanji_list。 但我遇到了2個問題:

  1. 雖然我有remote: true在我的form_tag remote: true ,當我從下拉列表中選擇時,瀏覽器仍會導航到新頁面http://localhost:3000/search_kanjis_by_lesson?lesson=1但不會停留在索引頁面。
  2. 標題中的錯誤。 雖然我希望這個search_by_lesson只能通過ajax呈現,但我不希望在文件夾中有單獨的search_by_lesson.html.erb

這是我的index.html.erb

<%= form_tag search_kanjis_by_lesson_path(lesson: params[:lesson]), method: :get, remote: true do |f| %>
    <%= select_tag :lesson, options_for_select(@lessons), include_blank: true, onchange: "this.form.submit()" %>
<% end %>
<table class="ui celled padded striped table">
    <thead>
        <tr>
            <th>Kanji</th>
            <th>Meaning</th>
            <th>Lesson</th>
        </tr>
    </thead>
    <tbody class="kanji_list">
        <%= render 'index' %>
     </tbody>
</table>

我使用partial來呈現列表_index.html.erb

<% @kanjis.each do |kanji| %>
    <tr>
        <td><%= kanji.word %></td>
        <td><%= kanji.meaning %></td>
        <td><%= kanji.lesson %></td>
    </tr>
<% end %>

我在路線上得到了這個

resources :kanjis

get '/search_kanjis_by_lesson', to: 'kanjis#search_by_lesson', as: :search_kanjis_by_lesson

在我的kanjis_controllers.rb中

class KanjisController < ApplicationController 

    # ... other generic actions: edit, show ...

    def index
        @kanjis = Kanji.all
        @lessons = [*1..32]     # @lessons is just an array of int.
    end

    def search_by_lesson
        @kanjis = Kanji.find_by_lesson params[:lesson]
    end
end

最后,我有一個search_by_lesson.js.erb

$("#kanji-list").html("<%= escape_javascript(render 'index') %>")

這應該適合你

在index.html.erb中

<%= form_tag search_kanjis_by_lesson_path, method: :get, remote: true do %>
<%= select_tag :lesson, options_for_select(@lessons), include_blank: true %>
<% end %>

在您的application.html.erb中

$(document).ready(function(){
 $('#lesson').change(function(){
  $('form').submit();
 });
});

在你的KanjisController中

    def search_by_lesson
      @kanjis = Kanji.find_by_lesson params[:lesson]
      respond_to do |format|
       format.js
      end
    end

在您的search_by_lesson.js.erb中

$(".kanji_list").html("<%= escape_javascript(render 'index') %>")

暫無
暫無

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

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