LoginSignup
12
13

More than 5 years have passed since last update.

RailsのオブジェクトをJavaScriptに渡す

Posted at

RubyからJSON形式に変換

配列からJSONへ

[1, 2, 3].to_json
=> "[1,2,3]"

ハッシュからJSONへ

{ "hash" => { "foo" => 1, "bar" => 2 } }.to_json
=> "{\"hash\":{\"foo\":1,\"bar\":2}}"

ActiveRecordからJSONへ

User.last.to_json
=> "{\"id\":2,\"name\":\"田中\",\"created_at\":\"2014-11-29T03:02:30.449-06:00\",\"updated_at\":\"2014-11-29T03:02:30.449-06:00\"}"

JSONをJavascriptに渡す

<div id='user' data-json='{"key":"value"}'></div>
$(function(){
    json = $('#user').data('json');
    //=>{key:value}
    typeof(json);
    //=>object
});

JSONの文字列はシングルコーテーションは使えないので注意

参考

12
13
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
12
13