LoginSignup
0
0

More than 3 years have passed since last update.

非同期処理の実装(シンプルバージョン)

Last updated at Posted at 2020-06-12

背景

以下画面から検索を行った時、リストが表示される仕組みについて、非同期処理を実装したい。

image.png

環境

項目 内容
OS.Catalina v10.15.4
Ruby v2.5.1
Ruby On Rails v5.2.4.3

内容

対応1)検索ボタン押下時に呼び出されるアクションと紐つくビューをhtml→jsに変更する
以下、index.html画面から呼び出されるアクションについて、1行目の「remote: :true」を記述。

index.html.erb(一部抜粋)
1        <%= form_tag(wordsearch_krowns_path, method: :get ,remote: :true) do %>
2          <input class="search-box__query" name="keyword" placeholder="作品名で検索" type="text" value="">
3            <button class="search-box__btn" title="検索" type="submit">
4              <i class="fas fa-search"></i>
5            </button>
6          </input>
7        <% end %>

こうすることで、「wordsearch」アクション=同名のアクションが呼ばれたのち、ビュー展開が「wordsearch.html.erb」→「wordsearch.js.erb」となる。

元々の画面描写は以下の通りレンダリングしている。13行目で検索結果リストをテーブルにて表示。ここを非同期で再描写する。

wordseach.html.erb(非同期する前のerbファイル)
 1 <!-- 詳細画面 -->
 2 <title>subaco トップページ</title>
 3 
 4 <div class="contents">
 5   <!-- サイドコンテンツ(左側)表示 -->
 6   <%= render "./shared/sidecontents" %>
 7 
 8 <div class="main-contents">
 9   <!-- メインコンテンツヘッダ部表示 -->
10   <%= render "mainheader"%>
11 
12   <!-- メインテーブル定義 -->
13   <%= render "maintable" %>
14 
15   <!-- クラウン表示 -->
16   <%= render "mainknowledge" %>
17 
18   <!-- クラウンイメージ表示 -->
19   <%= render "mainimage" %>
20 
21   <!-- main-contents 終了タグ -->
22   </div>
23 
24 <!-- contents 終了タグ -->
25 </div>



対応2)非同期処理を実装する
以下の1行のみで完了。非常にカンタン。作法は、対象となるhtmlのクラスと、レンダリングするための記述のみ。

wordseach.js.erb(非同期を行う処理)
$('.main-tab').html("<%= escape_javascript(render 'maintable' ) %>");

これだけの改修で、非同期処理を実装出来るようになります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0