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

More than 3 years have passed since last update.

posted at

updated at

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

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

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
45
Help us understand the problem. What are the problem?