LoginSignup
9
9

More than 5 years have passed since last update.

Railsのremotipartのresponseをjavascriptではなくjsonにする方法

Last updated at Posted at 2013-08-06

https://github.com/JangoSteve/remotipart のReadmeにはRailsでejsでJavaScriptをレスポンスで返してブラウザで実行する例が上げられていますが、そうではなくjsonを返したくて調査しました。

結論としては以下の対応でOKです。

  • formタグにdata-type="json"属性を指定する。
  • railsのコントローラではrespond_toのブロック内でformat.jsではなくformat.jsonでjsonを返す。
  • formのajax:successイベントのハンドラfunction (evt, data, status, xhr)のdataにjsonオブジェクトが受け取れます。

関連ソースでdataTypeを扱っている箇所

remotipart側は未設定ならscriptにするようになっています。
https://github.com/JangoSteve/remotipart/blob/v1.2.1/vendor/assets/javascripts/jquery.remotipart.js#L44-L45

jquery.remotipart.js
          // Modify some settings to integrate JS request with rails helpers and middleware
          if (settings.dataType === undefined) { settings.dataType = 'script *'; }

jquery-railsのjquery_ujs.jsではdata-type属性に設定されていればそれを使うようになっています。
https://github.com/rails/jquery-rails/blob/v3.0.4/vendor/assets/javascripts/jquery_ujs.js#L90

jquery_ujs.js
        dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType);
9
9
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
9
9