1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Rails6.0]〇〇.js.erb内でjQueryを使う

1
Posted at

前提

  • webpackを使用している
  • application.jsに紐付けているファイル(require(〇〇);)は問題なく、動作する
  • remote: trueでフォームからコントローラーにHTTPリクエストを投げると、 Uncaught ReferenceError: $ is not definedとエラーが出る

結論

結論から言うと,
以下のコードを追加する。

JavaScript/packs/application.js

// 省略
require("../new")
require("../pulldown")
require("../flash")

// ここから
window.$ = jQuery;
// ここまで追加

これで$("#hoge").html("<%= j(render "Fuga") %>");のように〇〇.js.erbでjQueryが使えるようになる。

remote: trueを使ったAjaxの流れ

  1. 【view】フォームからHTTPリクエストを送る。form_withのオプションはremote: trueを選択
  2. 【routes】HTTPリクエストを元にコントローラーとアクションを決める
  3. 【controller】アクション内の動作を行う。ここでjs形式でデータを返す
  4. 【controller】アクション名.js.erbviews/コントローラー名から指定する
  5. 【view】指定されたアクション名.js.erbが動作を行う
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?