9
6

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.

【Sinatra】Ajaxでサーバーへpost送信し戻り値(JSON)を受け取って表示

Last updated at Posted at 2016-12-20

Sinatraにて、Ajaxでサーバーへデータをpost送信し戻り値(JSON)をJavaScriptで受け取って表示するやり方です。
##本体

main.rb
require 'sinatra'
require 'sinatra/reloader'
require 'json'

get '/' do
  erb :index
end

post '/post' do
  #ここで入力データを処理する
  foo = params[:foo]
  bar = params[:bar]
  data = {
    "foo" => foo,
    "bar" => bar
  }
  content_type :json
  @data = data.to_json  
end

##ビュー

public/index.erb
<body>
  <!--データ入力フォーム-->
  <input type="text" id="foo">
  <input type="text" id="bar">
  <input id="submit" type="button" value="submit">
  <p id="result"></p>
  
  <!--jQuery召喚-->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
  
  <!--submitボタンをおすと以下のAjax通信-->
  <script type="text/javascript">
    $(function(){
      $("#submit").click(function(){
        var foo = $("#foo").val();
        var bar = $("#bar").val();
        $.ajax({
          type: "POST",
          url: "/post",
          dataType: "text", //dataTypeをちゃんと指定する
          data: {
            foo: foo,
            bar: bar
          },
        //以下、コールバック関数で戻り値を受け取り、id="result"に表示
        success: function(json) {
        dataType: "json",  //dataTypeをちゃんと指定する
        $('#result').append(json);
        },
        error: function() {
        $('#result').append('error');
        }
        });
      });
    });
  </script>
</body>

##結果
####before
before

####[submit]をおすと
submit

###できた!

9
6
2

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
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?