24
19

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.

RailsからJavaScriptへ配列を渡す方法

Posted at

RailsからJavaScriptへ配列の渡し方がわからなかったので、調べた結果のメモです

解決方法

Rails側の配列を一旦Jsonにし、JavaScript側でそのJsonをパースし配列にしました
受け渡しには inputタグ を使いました

Rails側のコード

rails
def index
  @arr = ["りんご", "ゴリラ", "ラッパ", "パイナップル"]
  # 配列をJsonへ変換する 
  @arr_json = @arr.to_json.html_safe
end

html.erb側のコード

html.erb
<input name="arr_json" type="hidden" value=<%= @arr_json %> class='arr_json'/>

JavaScript側のコード

js
// arr_json取得
var arrJson = $('.arr_json').val();
// arr_jsonをパースし配列にする
var arr = JSON.parse(arrJson);
// 確認用のログ出力
console.log(arr);
24
19
1

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
24
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?