JavaScriptでフォームデータを送信する
May 09, 2017
JavaScript でフォームデータを送信する方法のメモです。
FormData オブジェクトを使う
FormData
オブジェクトを使ってデータを送信します。
ファイルの送信などに重宝します。
使い方は簡単で、key-value 形式で送信するデータを詰め込むだけです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fb = new FormData() | |
fb.append('name', 'saitoxu') | |
fb.append('email', 'saitoxu@example.com') |
詳しくはこちら ↓
サンプル
React/Rails で使った場合のサンプルを載せておきます。
クライアントは以下のようになります。
FormData.append()
のキーをサンプルのようにすると、
通常の Rails のフォームデータ受信と同じようにデータを受け取れます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
onSubmit(e) { | |
e.preventDefault() | |
const fd = new FormData() | |
fd.append('user[name]', this.state.name) | |
fd.append('user[email]', this.state.email) | |
fetch('http://example.com/users', { | |
method: 'POST', | |
body: fd | |
}).then(response => | |
response.json() | |
).then((json) => { | |
// do something | |
}).catch(err => | |
console.log(err) | |
) | |
} |
サーバサイドはこんな感じです。 通常の Rails と変わったところはないですね。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UsersController < ApplicationController | |
def create | |
user = User.new(user_params) | |
if user.save | |
render json: { status: 'success' } | |
else | |
render json: { status: 'failure' } | |
end | |
end | |
private | |
def user_params | |
params.require(:user).permit(:name, :email) | |
end | |
end |