LoginSignup
33
46

More than 5 years have passed since last update.

Flask + jQuery(ajax)でページ遷移せずにform入力データを送る

Last updated at Posted at 2017-09-26

Flask(PythonのWebフレームワーク)とjQueryのajaxを使って、formの内容を非同期通信で送る方法です。

クライアント側

HTML

<form class='ajax_submit' method="post" action="/toPostURL">
  <input type="text" name="username">
  <input type="text" name="age">
  <button>Submit</button>
</form>

jQuery

$('.button').on('click', function(){
  $.ajax({
    url: $(this).parent('form').attr('action'),
    type: 'post',
    data: $(this).parent('form').serialize()
  });
});

serialize()により、指定したform内の値がusername=[入力値]&age=[入力値]のように変換される。便利だ。

※submitボタンをtype='submit'なんかで指定している場合は、event.preventDefault();で本来のPOST機能の取り消す処理を忘れずに!

サーバー側

Python

@app.route('/toPostURL', methods=['POST'])
def get_user_info():
    username =  request.form['username'];
    age = request.form['age'];
    response = Response()
    response.status_code = 200
    return response

実装環境

Flask : 0.12.2
Python : 3.5.2

お世話になったページ

Python Flask jQuery Ajax POST

33
46
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
33
46