25
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

Sinatraでformを使ってPOSTしてみる

はじめに

  1. http://qiita.com/ms2sato/items/7c07b2079b48c49fad2a
  2. http://qiita.com/ms2sato/items/eed1e3c929ac8f6195a9
  3. http://qiita.com/ms2sato/items/5bd201c84dab858ee501

の続き。

今度は簡単にデータをPOSTしてみる。問い合わせ内容を入力して、その内容を確認するまで。

index.erbでformを表示するように修正

<html>
<head>
  <meta charset="UTF-8">
</head>
<body>
  <p>
    <a href="about">このサービスについて</a>
  </p>
  <h1>お問い合わせ</h1>
  <form action="confirm" method="POST">
    <div>
      email:<input type="text" name="email" value="">
    </div>
    <div>
      本文:
      <textarea name="message" rows="5"></textarea>
    </div>
    <div>
      <input type="submit" value="送信する">
    </div>
  </form>
</body>
</html>

app.erbでPOSTされたデータを受け取ってみる

require 'sinatra'
require 'sinatra/reloader'

get '/' do
  erb :index  
end

get '/about' do
  erb :about
end

post '/confirm' do
  @email = params[:email]
  @message = params[:message]
  erb :confirm
end

confirm.erbで受け取ったデータを確認する

<html>
<head>
  <meta charset="UTF-8">
</head>
<body>
  <h1>お問い合わせ内容確認</h1>
  <div>
    <div>
      email: <%=@email%>
    </div>  
    <div>
      本文:
      <p>
        <%=@message%>
      </p>
    </div>    
  </div>
</body>
</html>

おしまいに

これで、トップ画面でemail本文を入れて、次の画面で入れた内容を確認できればOK!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
25
Help us understand the problem. What are the problem?